c# - Windows 服务 - 它可以运行两个以不同时间间隔安排的独立任务吗

标签 c# .net service windows-services

我编写了一个 Windows 服务,它在每周的特定时间触发一次电子邮件。该服务运行得很好。代码如下:

  protected override void OnStart(string[] args)
    {
        this.Log("Simple Service Started");
        this.ScheduleService();
    }

    protected override void OnStop()
    {
        this.Log("Simple Service Stopped");
        this.Schedular.Dispose();
    }

    private Timer Schedular;

    public void ScheduleService()
    {
        try
        {
            Schedular = new Timer(new TimerCallback(SchedularCallback));
            // Code that schedules the Callback
        }
     }

    private void SchedularCallback(object e)
    {
        try
        {
                  // Scheduled Job code
         }
     }

现在我有另一个类似的要求,我必须触发另一封电子邮件,但它的时间表必须在 2 周内一次。有没有办法可以将这项工作容纳在同一个服务中,或者我必须编写另一个服务?

最佳答案

我曾经在我的一个项目中做过类似的设计。 尝试使用一个基本抽象“ScheduledTask”类来定义您的计时行为,并让继承的任务类使用它。

这是我为计时器所做的,我认为将其更改为调度程序只需要很少的工作。

internal abstract class TaskBase
{
    /// <summary>
    /// Task timer
    /// </summary>
    private readonly Timer _timer;

    /// <summary>
    /// Set refresh time
    /// </summary>
    protected int TimeRefreshSec { get; private set; }

    /// <summary>
    /// Loop of timePassed
    /// </summary>
    protected int TimePassed { get; private set; }

    protected TaskBase(double refreshInterval)
    {
        TimeRefreshSec = (int) refreshInterval / 1000;
        TimePassed = 0;

        _timer = new Timer(refreshInterval) { AutoReset = true };
        _timer.Elapsed += Tick;
    }

    private void Tick(object sender, ElapsedEventArgs e)
    {
        TimePassed += TimeRefreshSec;

        Tick();
    }

    public void Start()
    {
        ResetTimer();

        // Run the task once when starting instead of waiting for a full interval.
        Tick();
        OnStart();
    }

    public void Stop()
    {
        if (_timer.Enabled)
        {
            _timer.Stop();
            OnStop();
        }
    }

    protected virtual void ResetTimer()
    {
        TimePassed = 0;
        if (_timer.Enabled) _timer.Stop();
        _timer.Start();
    }

    /// <summary>
    /// Implement here a specific behavior when task is stopped.
    /// </summary>
    protected abstract void OnStop();

    /// <summary>
    /// Implement here a specific behavior when task is started.
    /// </summary>
    protected abstract void OnStart();

    /// <summary>
    /// This method is executed each time the task's timer has reached the interval specified in the constructor.
    /// Time counters are automatically updated.
    /// </summary>
    protected abstract void Tick();
}

和服务:

public partial class MyService : ServiceBase
{
    private readonly List<TaskBase> _tasks; 

    public MyService()
    {
        InitializeComponent();

        // Add in this list the tasks to run periodically.
        // Tasks frequencies are set in the corresponding classes.
        _tasks = new List<TaskBase>
        {
            new InheritingTask(),
            new OherInheritingTask()
        };
    }

    protected override void OnStart(string[] args)
    {
        try
        {
            _tasks.ForEach(t => t.Start());
        }
        catch (Exception ex)
        {
            Stop();
        }
    }

    protected override void OnStop()
    {
        _tasks.ForEach(t => t.Stop());
    }
}

编辑:

类继承TaskBase的代码:

class InheritingTask: TaskBase
{
    public InheritingTask()
        : base(Settings.Default.InheritingTaskInterval) // In milliseconds
    {
        //TODO: Custom initialization here
    }

    protected override void Tick()
    {
        //TODO: Task logic here
    }

    protected override void OnStart()
    { }

    protected override void OnStop()
    { }

    protected override void ResetTimer()
    {
        //TODO: Custom reset logic here
        base.ResetTimer();
    }
}

关于c# - Windows 服务 - 它可以运行两个以不同时间间隔安排的独立任务吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31988775/

相关文章:

c# - 如何在 ListView 的图像列表中添加系统图标

c# - WPF MVVM - 如何检测 View 是否为 "Dirty"

.net - 生成 .NET 后台工作程序

java - 使用 Volley 时后台服务出现 OutofMemory 错误

c# - Task.WhenAny 会取消注册未完成任务的延续吗?

c# - 获取特定月份的天数

c# - 添加用户控件

c# - 数据库中的跟踪错误

Android 服务和 UI 线程

Android屏幕方向数据丢失预防