在某个时间每24小时定时一次

时间:2013-09-13 20:09:09

标签: c# timer

我想创建一个在特定时间每24小时调用一次方法的计时器。我不希望通过Windows Scheduler执行此操作,而应该在代码中完成。以下是我目前使用的代码:

DateTime now = DateTime.Now;
DateTime today = now.Date.AddHours(16);
DateTime next = now <= today ? today : today.addDays(1);

Systems.Threading.TimerCallback callback = new TimerCallback(DisplayMessage);
Systems.Threading.Timer timer = new System.Threading.Timer(callback, null, next - now, TimeSpan.FromHours(24));

我的问题是,如果next最终离当前时间只有几分钟的距离,那么代码就可以运行并通过DisplayMessage()显示消息。如果时差大于几分钟,则代码不起作用,没有异常,崩溃或任何其他内容。我尝试在DisplayMessage()中放置日志语句,消息框和断点,以确保我能够正确地看到调用DisplayMessage()的时间,但没有运气。

2 个答案:

答案 0 :(得分:0)

这是一个有效的例子。

public class Scheduler {
    private readonly List<Task> _Tasks;
    private Timer _Timer;

    public Scheduler() {
        _Tasks = new List<Task>();
    }

    public void ScheduleTask(Task task) {
        _Tasks.Add(task);
    }

    public void CancelTask(Task task) {
        _Tasks.Remove(task);
    }

    //Start the timer.
    public void Start() {
        //Set the interval based on what amount of accurcy you need.
        _Timer = new Timer {
            Interval = 1000
        };

        _Timer.Elapsed += (sender, args) => UpdateTasks();
        _Timer.Enabled = true;
    }

   //Check to see if any task need to be executed.
    private void UpdateTasks() {
        for (int i = 0; i < _Tasks.Count; i++) {
            Task task = _Tasks[i];

            if (task.ExecuteTime >= DateTime.Now) {
                task.Callback();
                _Tasks.Remove(task);
            }

            _Tasks.Remove(task);
        }
    }

    //Stop the timer when you are done.
    public void Stop() {
        _Timer.Dispose();
    }
}

//Use this to schedule a task.
public class Task {
    public DateTime ExecuteTime { get; set; }
    public Action Callback { get; set; }

    public Task(DateTime executeTime, Action callback) {
        ExecuteTime = executeTime;
        Callback = callback;
    }
}

答案 1 :(得分:-2)

我认为更好的解决方案是让时间每秒触发并检查时间和任何你想要的东西,我不认为每秒触发它是一个昂贵的过程。 每24小时触发一次不是计时器的正常使用

相关问题