我有一组项目,每天只需在特定时间运行一次。我当时想将每个项目都作为Web服务运行,并使用Timer或Task.Delay安排工作,但是计时器/任务是否适合长时间空闲的工作安排?
这是我的调度程序配置,以及如何创建计时器。所有配置都存储在数据库中。
public class ScheduledTaskStructure : IDisposable
{
private Timer _timer;
public void Start()
{
_timer = new Timer();
_timer.Interval (new TimeSpan(24,0,0)).TotalMilliseconds;
_timer.AutoReset = false;
_timer.Elapsed += _timer_Elapsed;
}
private Assembly _Assembly;
private object _instance;
private Type _classType;
MethodInfo _MethodInfo;
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Stop();
if (_Assembly == null)
{
_Assembly = Assembly.LoadFrom(ModuleName);
_instance = _Assembly.CreateInstance(ClassName, true);
_classType = _Assembly.GetType(ClassName, true, true);
_MethodInfo = _classType.GetMethod(MethodName);
}
_MethodInfo.Invoke(_instance, null);
_timer.Start();
}
public void Stop()
{
if (_timer != null)
{
_timer.Stop();
_timer = null;
}
}
public volatile bool IsRunning { get; set; }
#region IDisposable Members
public void Dispose()
{
_timer = null;
}
#endregion
public string Task { get; set; }
public DateTime NextRun { get; set; }
public string TimeInterval { get; set; }
public string ModuleName { get; set; }
public string ClassName { get; set; }
public string MethodName { get; set; }
public string Status { get; set; }
public bool IsUsed { get; set; }
}
最佳答案
通常,像这样使用Timer并不是很好,而在IIS中则更糟-IIS会专门杀死空闲进程(除非您将其配置为不运行或ping通以使其保持活动状态)。
在任何情况下,您实际上都在运行,并且不必要地占用23:59:00的资源,您的程序实际上并没有做任何事情,并且有可能将其杀死或在任何时候使它暴露。
有更好的构造可以在指定的时间运行事物。其中最简单的就是将您的应用程序添加到Windows Task Scheduler中。
对于更复杂的要求,编写Windows服务来查询计划配置并在所需时间运行进程可能是解决方法。
关于c# - 计时器或任务是否适合长时间空闲的任务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29962416/