【问题标题】:Invoke objects' method at a specific time C#在特定时间调用对象的方法 C#
【发布时间】:2015-06-29 19:08:12
【问题描述】:

我有点困惑,正在寻求建议。

我想做什么的想法:

Program started 
foreach file in directory 'tasks'
   Deserialize file to object
   DateTime date = GetExcecutionDate()
   if (Date.Now.DateDiff(date) < 0)
        async object.Excecute()
   else
        //Set task for file to execute at date
End foreach
Programs continue executing


When Task is called, I need to know filename
async
    Deserialize file to object
    object.Execute();
    ReloadTask(filename); //Sets new fire time for this file 

实现此机制的最佳方式是什么。我所需要的只是如何强制程序调用将在特定时间接收字符串的特定方法。我应该以哪种方式挖掘 - Timers 或 Taskers 或其他东西?

【问题讨论】:

  • 只需创建一个包含datefilename 的类,然后创建一个List&lt;ClassName&gt; 来保存这些实例。现在使用标准 Timer 控件并将其 Interval 设置为您想要检查日期/时间是否已通过的频率(每分钟一次?)。在 Timer 的 Tick 事件中,遍历列表并查看是否应处理任何项目...

标签: c# scheduled-tasks


【解决方案1】:

您可以获取下一次运行的时间并减去 now() 并设置一个计时器来运行您的操作:

TimeSpan timeSpan = date.Subtract(DateTime.Now.AddSeconds(1));
double interval = timeSpan.TotalMilliseconds;
Timer _timer = new Timer();
_timer.Interval = interval;
_timer.Elapsed += PerformAction ;
_timer.AutoReset = false;
_timer.Start();

在某处使用 PerformAction:

public void PerformAction (object sender, ElapsedEventArgs e)

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2013-05-15
    • 2011-06-04
    • 2011-03-15
    相关资源
    最近更新 更多