每周严格按星期一凌晨4点运行的Windows服务

时间:2016-04-04 16:21:02

标签: c# windows-services

我有这项服务必须每周一凌晨4点每周运行一次。通过Google搜索我想出了这段代码:

Timer ServiceTimer;
DateTime scheduleTime;

private void ScheduleRun()
{
    int daySet = (Convert.ToInt16(Settings.Default.DayOfWeekRun) - (int)DateTime.Today.DayOfWeek + 7) % 7;
    scheduleTime = DateTime.Today.AddDays(daySet).AddHours(Convert.ToDouble(Settings.Default.TimeOfDayRun));
    if (daySet == 0 && scheduleTime < DateTime.Now)
    {
        scheduleTime = DateTime.Today.AddDays(7).AddHours(Convert.ToDouble(Settings.Default.TimeOfDayRun));
    }
}

public Airt_Service()
{
    InitializeComponent();
    ServiceTimer = new System.Timers.Timer();
    ScheduleRun();
}

protected void ServiceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    TimeSpan ts = new TimeSpan(7, 0, 0, 0);
    runProcessCode();
}

protected override void OnStart(string[] args)
{
    ServiceTimer.Interval = scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
    ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(ServiceTimer_Elapsed);
    ServiceTimer.Start();
}

这里似乎缺少什么?我已经尝试过调试它,似乎工作(间隔2分钟)。间隔为1周(以毫秒为单位)是否有问题?

2 个答案:

答案 0 :(得分:4)

The Windows Task Scheduler is perfect for running a task once a week. Ideally you would write a console application that does whatever you want to do and setup a basic task to run it on Mondays at 4 AM.

答案 1 :(得分:-1)

我不会编写自己的调度程序。 我会使用Quartz

有一些jQuery插件可用于生成CRON表达式。

您可以在我的存储库中查看工作代码:
https://github.com/ststeiger/CronSharp