Bre*_*gan 8 c# scheduled-tasks job-scheduling
我正在考虑编写一个Windows服务,它将在用户指定的时间打开或关闭某个功能(使用我将提供的配置实用程序).基本上,用户将指定PC将进入"仅工作"模式(阻止Facebook和其他分散注意力的站点)的某些时间,然后当这些时间到来时,PC将返回到正常模式.
我已经想出了一些方法来创建"仅限工作"模式,但我正在努力的是如何知道何时进出该模式.我真的不想使用线程和计时器,如果我可以避免它,因为这似乎会产生大量的开销,所以我正在寻找的将是某种方式:
有谁知道最好的方法吗?
我认为你可以用你提到的Windows服务很好地实现它.在我们的一个制作系统中,我们有一个以下面的方式实现的Windows服务(不同的核心功能),现在已经安全运行了近三年.
基本上,以下代码的目的是每次内部timer(myTimer)唤醒时服务执行某种方法.
以下是基本实现.在此示例中,您的核心功能应放在方法中EvalutateChangeConditions,该方法应该每60秒执行一次.我还将为您的管理客户提供一种公共方法,以了解当前的"工作模式".
public partial class MyService : ServiceBase
{
private System.Threading.Thread myWorkingThread;
private System.Timers.Timer myTimer = new System.Timers.Timer();
// [...] Constructor, etc
protected override void OnStart(string[] args)
{
// Do other initialization stuff...
// Create the thread and tell it what is to be executed.
myWorkingThread = new System.Threading.Thread(PrepareTask);
// Start the thread.
myWorkingThread.Start();
}
// Prepares the timer, sets the execution interval and starts it.
private void PrepareTask()
{
// Set the appropiate handling method.
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
// Set the interval time in millis. E.g.: each 60 secs.
myTimer.Interval = 60000;
// Start the timer
myTimer.Start();
// Suspend the thread until it is finalised at the end of the life of this win-service.
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Get the date and time and check it agains the previous variable value to know if
// the time to change the "Mode" has come.
// If does, do change the mode...
EvalutateChangeConditions();
}
// Core method. Get the current time, and evaluate if it is time to change
void EvalutateChangeConditions()
{
// Retrieve the config., might be from db? config file? and
// set mode accordingly.
}
protected override void OnStop()
{
// Cleaning stuff...
}
}
Run Code Online (Sandbox Code Playgroud)