如何使用C#使用计时器运行其他进程

时间:2018-12-06 08:01:32

标签: c# timer

下面的代码每1分钟运行一次

public partial class EmailService : ServiceBase
{
    private Timer timer = null;
    public EmailService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer = new Timer();
        this.timer.Interval = 60000;
        this.timer.Elapsed += new ElapsedEventHandler(this.timer_Tick);
        this.timer.Enabled = true;
        Library.WriteErrorLog("Notification Service started.");
    }
    private void timer_Tick(object sender, ElapsedEventArgs e)
    {
        try
        {
            NotificationManager.ProcessApprovalNotifications();
            NotificationManager.CreateRenewalNotifications();
            NotificationManager.ProcessRenewalNotifications();
        }
        catch (Exception ex)
        {
            Library.WriteErrorLog("FAC VMS Notification Service Error: " + ex.Source);
            Library.WriteErrorLog("FAC VMS Notification Service Error: " + ex.Message);
            Library.WriteErrorLog("FAC VMS Notification Service Error: " + ex.StackTrace);
        }
        Library.WriteErrorLog("FAC VMS Notification Service Run");
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
        Library.WriteErrorLog("Notification Service stopped.");
    }
}

如何使进程根据下面的列表运行?

  • 每天一次= NotificationManager.CreateRenewalNotifications()
  • 每1分钟= NotificationManager.ProcessApprovalNotifications()
  • 每1分钟= NotificationManager.ProcessRenewalNotifications()

1 个答案:

答案 0 :(得分:2)

您可能还记得在类字段中最后一次调用NotificationManager.CreateRenewalNotifications时的DateTime,并且只有在经过一天后才再次调用它:

private Timer timer = null;
private DateTime lastCalledCreateRenewalNotifications = DateTime.MinValue;

NotificationManager.ProcessApprovalNotifications();
if (DateTime.Now - lastCalledCreateRenewalNotifications >= TimeSpan.FromDays(1))
{
    NotificationManager.CreateRenewalNotifications();
    lastCalledCreateRenewalNotifications = DateTime.Now;
}
NotificationManager.ProcessRenewalNotifications();