Здравствуйте, Бенджамин Арансибия, вы можете сделать это следующим образом:
В его App.config добавьте переменные, чтобы контролировать, когда задача будет выполняться.
<appSettings>
<add key="executeDailyService" value="true"/>
<add key="dailyServiceTime" value="08:00-18:00"/>
<add key="dailyServiceInterval" value="1"/>
</appSettings>
executeDailyService = Опция, указывающая, будет ли задача выполняться каждый день dailyServiceTime = Опция для указания периода, в течение которого она может выполняться, здесь можно настроить, например: 13:00-14:00 dailyServiceInterval = Опция, указывающая диапазон дней, в которые будет выполняться задача например:. 1 = каждый день, 2 = через день ... п
При запуске приложения запустите следующий метод:
private void startTimer()
{
// Loads the variables that will be used
var executeDailyService = ConfigurationManager.AppSettings["executeDailyService"];
var dailyServiceTime = ConfigurationManager.AppSettings["dailyServiceTime"];
var dailyServiceInterval = ConfigurationManager.AppSettings["dailyServiceInterval"];
// Validates that the variables are loaded
if (executeDailyService != "true" || String.IsNullOrEmpty(dailyServiceTime) || String.IsNullOrEmpty(dailyServiceInterval))
return;
// Timer that controls the automatic execution of code
var timer = new Timer();
timer.Interval = Convert.ToInt32(dailyServiceInterval) * 60 * 1000; // Calculates how often will run your code
timer.Elapsed += new ElapsedEventHandler(services);
timer.Start();
}
private void services(object sender, ElapsedEventArgs e)
{
// Loads of the variable time period
var dailyServiceTime = ConfigurationManager.AppSettings["dailyServiceTime"];
// Validates the contents of the variable is in the correct format
if (String.IsNullOrEmpty(dailyServiceTime) || !dailyServiceTime.IsMatch("^\\d{2}:\\d{2}-\\d{2}:\\d{2}$"))
return;
// Calculates whether the current time is within the range you set
var now = Util.Now();
var dateBegin = Util.DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(dailyServiceTime.Substring(0, 2)), Convert.ToInt32(dailyServiceTime.Substring(3, 2)), 0);
var dateEnd = Util.DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(dailyServiceTime.Substring(6, 2)), Convert.ToInt32(dailyServiceTime.Substring(9, 2)), 0);
if (dateBegin > dateEnd || now < dateBegin || now > dateEnd)
return;
var timer = sender as Timer;
timer.Stop();
// You code here
timer.Start();
}
person
picossi
schedule
05.12.2014