当计时器倒计时为0时调用方法

时间:2013-03-27 15:57:28

标签: c# service methods timer onstart

我正在编写一个C#服务,其主要功能是从数据库中提取照片并将其保存到目录中,每天两次。此操作通常需要大约15分钟(有很多照片)。如果我把逻辑放在OnStart()中运行程序,那么在启动服务报告一分钟左右之后它就没有成功启动。这是因为它在OnStart()方法中的时间太长了。

如何在OnStart()方法中设置一个定时器,在大约一分钟后调用我的RunApp()方法?

编辑:这是一些代码。在设置使其每天运行的调度程序之后,我还想简单地运行它。我认为设置一个大约一分钟的计时器会起作用,这样就有时间退出OnStart()方法。然后当计时器关闭时,应用程序将运行。

protected override void OnStart(string[] args)
{
    Scheduler sch = new Scheduler("Photo Sync");

    try
    {
      MailConfiguration mailConfig = new MailConfiguration(Properties.Settings.Default.EmailLogTo, Properties.Settings.Default.EmailLogFrom,
                                                           "Photo Sync Photo Service error", Properties.Settings.Default.SmtpServerIp, "Photo Sync");
      sch.MailComponent = mailConfig;
    }
    catch
    {

    }

    sch.SchedulerFired += new EventHandler(RunApp);

    try
    {
      sch.ScheduleDaily(Properties.Settings.Default.DailyScheduledTime);
    }

    RunApp();
}

3 个答案:

答案 0 :(得分:1)

通常,启动Windows服务的正常过程是创建一个线程,并让该线程执行服务处理,允许OnStart及时退出Windows。线程仍然在后台处理东西。例如:

protected CancellationTokenSource _tokenSource = null;

protected override void OnStart(string[] args)
{
    _tokenSource = new CancellationTokenSource();

    Task processingTask = new Task(() =>
       {
           while(!_tokenSource.IsCancellationRequested)
           {
               // Do your processing
           }
       });

    processingTask.Start();
}

protected override void OnStop()
{
    _tokenSource.Cancel();
}

如果您的服务无需无限期运行,那么您可能需要考虑计划任务。

答案 1 :(得分:1)

在您在服务的OnStart方法中启动的单独线程中运行保存功能。像这样:

protected override void OnStart(string args[])
{

    // your other initialization code goes here

    // savePhotos is of type System.Threading.Thread
    savePhotosThread = new Thread(new ThreadStart(SavePhotos));
    savePhotosThread.IsBackground = true;
    savePhotosThread.Name = "Save Photos Thread";
    savePhotosThread.Start();

}

You'll place the functionality for saving the files in the `SavePhotos` method, maybe something like this:

private void SavePhotos()
{

    // logic to save photos
}

我使用类似上面的代码来做日志记录(我每5分钟左右记录一次服务的统计信息),这是我几年前写的一个永远在线的服务。不要忘记将System.Threading添加到您的服务和using指令。

答案 2 :(得分:0)

    System.Threading.Timer Timer1 = new System.Threading.Timer(RunApp, null, 1000, System.Threading.Timeout.Infinite);

void RunApp(object State)
{
}