2015-05-25 24 views
0

我希望使进程/系统始终处于运行状态并在特定时间段内执行特定功能。如何使进程始终运行并在特定时间执行某个功能

例如,如果我希望系统每周发送一封电子邮件到特定地址,那我该怎么办?

+2

创建一个进程,调度它与Windows调度...你试过什么?问题是什么? –

+0

其实我还没有尝试过任何东西,因为我试图理解,并且从哪里开始 – ARC

+2

安排某些事情的最佳方式是使用OS Scheduler applciation,不要尝试创建您的调度程序,因为OS调度程序更稳定,支持长计时器周期等等......所以你只需要编写一个进程就可以做一次,并使用Windows或Linux调度程序进行计划 –

回答

2

运行总是:去为Windows服务 对于周期性的事:去定时器

所以有一个Windows服务,维护定时器设定在规定的时间间隔来触发,做任何你需要在那里。

0

这是我的例子,对于一些任务没关系。

public class Timer : IRegisteredObject 
{ 
    private Timer _timer; 
    public static void Start() 
    { 
     HostingEnvironment.RegisterObject(new Timer()); 
    } 

    public Timer() 
    { 
     StartTimer(); 
    } 

    private void StartTimer() 
    { 
     _timer = new Timer(BroadcastUptimeToClients, null, TimeSpan.FromSeconds(0), TimeSpan.FromMilliseconds(100));  
    } 
    private void BroadcastUptimeToClients(object state) 
    { 
     //some action 
    } 

    public void Stop(bool immediate) 
    { 
     //throw new System.NotImplementedException(); 
    } 
} 

在Global.asax中

Timer.Start(); 

在你的情况我会@阿尔森Mkrtchyan同意 - 使用OS调度器。 如果您想使用Windows服务,这里是如何会看你的服务:

partial class MyService 
{ 
    /// <summary> 
    /// Required designer variable. 
    /// </summary> 
    private System.ComponentModel.IContainer components = null; 

    private Timer _watcherTimer = new System.Timers.Timer(); 

    private static Logger logger = LogManager.GetCurrentClassLogger(); 
    /// <summary> 
    /// Clean up any resources being used. 
    /// </summary> 
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
    protected override void Dispose(bool disposing) 
    { 
     if (disposing && (components != null)) 
     { 
      components.Dispose(); 
     } 
     base.Dispose(disposing); 
    } 

    #region Component Designer generated code 

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    private void InitializeComponent() 
    { 
     components = new System.ComponentModel.Container(); 
     this.ServiceName = "MyService"; 

     this._watcherTimer.Interval = 6000; 
     this._watcherTimer.Enabled = false; 
     this._watcherTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer_Tick); 
    } 

    #endregion 
} 

partial class MyService : ServiceBase 
{ 
    public MyService() 
    { 
     try 
     { 
      InitializeComponent(); 
     } 
     catch (Exception e) 
     { 
      logger.Error("Error initializing service",e); 
      Stop(); 
     } 

    } 

    protected override void OnStart(string[] args) 
    { 
     _watcherTimer.Enabled = true; 
     logger.Info("Service has started at " + DateTime.UtcNow.ToLongDateString()); 
    } 

    protected override void OnStop() 
    { 
     logger.Info("Service has stopped at " + DateTime.UtcNow.ToLongDateString()); 
    } 

    private void Timer_Tick(object sender, ElapsedEventArgs e) 
    { 
     logger.Info("Timer Tick"); 
    } 
} 

安装:

[RunInstaller(true)] 
public class WindowsServiceInstaller : Installer 
{ 
    /// <summary> 
    /// Public Constructor for WindowsServiceInstaller. 
    /// - Put all of your Initialization code here. 
    /// </summary> 
    public WindowsServiceInstaller() 
    { 
     var serviceProcessInstaller = 
          new ServiceProcessInstaller(); 
     var serviceInstaller = new ServiceInstaller(); 

     //# Service Account Information 
     serviceProcessInstaller.Account = ServiceAccount.LocalSystem; 
     serviceProcessInstaller.Username = null; 
     serviceProcessInstaller.Password = null; 

     //# Service Information 
     serviceInstaller.DisplayName = "MY SERVICE DISPLAY NAME"; 
     serviceInstaller.Description = "MY SERVICE DESCRIPTION"; 
     serviceInstaller.StartType = ServiceStartMode.Automatic; 

     //# This must be identical to the WindowsService.ServiceBase name 
     //# set in the constructor of WindowsService.cs 
     serviceInstaller.ServiceName = "MyService"; 

     Installers.Add(serviceProcessInstaller); 
     Installers.Add(serviceInstaller); 
    } 
} 

与蝙蝠

static class Program 
{ 
    static void Main(string[] args) 
    { 
     if (args.Length > 0) 
     { 
      //Install service 
      if (args[0].Trim().ToLower() == "/i") 
      { System.Configuration.Install.ManagedInstallerClass.InstallHelper(new[] { "/i", Assembly.GetExecutingAssembly().Location }); } 

      //Uninstall service     
      else if (args[0].Trim().ToLower() == "/u") 
      { System.Configuration.Install.ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location }); } 
     } 
     else 
     { 
      var servicesToRun = new ServiceBase[] { new MyService() }; 
      ServiceBase.Run(servicesToRun); 
     } 
    } 
} 

INSTALL.BAT

运行此
@ECHO OFF 

    REM Prevent changing current directory when run bat file as administrator on win7 

    @setlocal enableextensions 
    @cd /d "%~dp0" 

    REM The following directory is for .NET 4.0 

    set DOTNETFX4=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 
    set PATH=%PATH%;%DOTNETFX4% 

    echo Installing WindowsService... 
    echo "%CD%\WindowsService\Service\bin\Debug\Service.exe" 
    echo --------------------------------------------------- 
    InstallUtil /i "%CD%\WindowsService\Service\bin\Debug\Service.exe" 
    echo --------------------------------------------------- 
    echo Done. 
    set /p DUMMY=Hit ENTER to continue... 

unistall.bat

 @ECHO OFF 

    REM Prevent changing current directory when run bat file as administrator on win7 

    @setlocal enableextensions 
    @cd /d "%~dp0" 

    REM The following directory is for .NET 4.0 

    set DOTNETFX4=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 
    set PATH=%PATH%;%DOTNETFX4% 

    echo Installing WindowsService... 
    echo --------------------------------------------------- 
    InstallUtil /u "%CD%\WindowsService\Service\bin\Debug\Service.exe" 
    echo --------------------------------------------------- 
    echo Done. 
    set /p DUMMY=Hit ENTER to continue... 

我的文件夹层次:

install.bat 
    uninstall.bat 
    service-project-folder 
     packages 
     project-folder 
     .sln file 
0

通过使用ReactiveExtensions,您可以使用以下代码,如果您有兴趣进行如打印到控制台那样简单的操作,请点击此处https://stackoverflow.com/questions/30473281/how-to-print-a-string-in-c-sharp-after-every-1-minute-using-timer。您可以通过NuGet添加Rx-Main来添加Reactive Extensions。

using System; 
using System.Reactive.Linq; 

namespace ConsoleApplicationExample 
{ 
    class Program 
    { 
     static void Main() 
     { 
      Observable.Interval(TimeSpan.FromMinutes(1)) 
      .Subscribe(_ => 
      {     
       Console.WriteLine(DateTime.Now.ToString()); 
      }); 
      Console.WriteLine(DateTime.Now.ToString()); 
      Console.ReadLine(); 
     } 
    } 
}