使用Windows服务定时去执行一个方法的三种方式

方式一:使用System.Timers.Timer定时器

public partial class Service1 : ServiceBase
    {
       
        private UnitOfWork unitOfWork;
        private System.Timers.Timer timer1;//初始化一个定时器        
        LogHelper lghelper = new LogHelper(typeof(Service1));
        public Service1()
        {
            InitializeComponent();
            unitOfWork = new UnitOfWork();
         this.timer1 = new System.Timers.Timer();
            this.timer1.Interval = 1000;//设置定时器启动的时间间隔
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);//定时器定时执行的方法          
        }

        protected override void OnStart(string[] args)
        {
            this.timer1.Enabled = true;//服务启动时开启定时器
            lghelper.Info("服务启动");
        }

        protected override void OnStop()
        {
            this.timer1.Enabled = false;//服务停止时关闭定时器
            unitOfWork.Dispose();
            lghelper.Info("服务停止");
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.timer1.Enabled = false;//在服务运行时关闭定时器,避免在服务还没有运行结束时达到定时器时间间隔又重头开始运行(比如该定时器设置为5分钟同步一次数据,当数据量很大时,5分钟同步不完,这时达到定时器时间间隔,又会重头开始同步,所以在服务开始运行时关闭定时器)
            lghelper.Info("服务开始运行");
            try
            {

                DoWork();
            }
            catch (Exception ex)
            {
                lghelper.Error(ex.ToString());
                lghelper.Info("服务运行失败");
                Thread.Sleep(5000);
            }

            this.timer1.Enabled = true;//服务运行结束,重新启动定时器
        }

       
    }

方式二:使用Task

  partial class Service2 : ServiceBase, IDisposable
    {
        LogHelper lghelper = new LogHelper(typeof(Service2));
        private CancellationTokenSource TokenSource = new CancellationTokenSource();
   protected UnitOfWork unitOfWork = new UnitOfWork();

        Task MainTask;
        public Service2()
        {
            InitializeComponent();
          

        }
        public void Dispose()
        {
            unitOfWork.Dispose();
        }

        protected override void OnStart(string[] args)
        {
            lghelper.Info("开启服务!");
            MainTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                      DoWork();

                    }
                    catch (Exception ex)
                    {
                        lghelper.Error(ex.ToString());

                        Thread.Sleep(60 * 60 * 1000);
                    }

                    Thread.Sleep(5 * 60 * 1000);
                }

            });

        }

        protected override void OnStop()
        {
            if (MainTask != null)
            {
                if (MainTask.Status == TaskStatus.Running) { }
                {
                    TokenSource.Cancel();
                    lghelper.Info("线程结束");
                }
            }
        }


     
    }

方式三:这个方法是看到博友的,还没有用过,不过觉得挺方便的

http://www.cnblogs.com/ldyblogs/p/timer.html

转载于:https://www.cnblogs.com/stubborn-donkey/p/7656284.html

你可以使用C#编写一个Windows服务定时执行任务。下面是一个简单的示例: 首先,创建一个新的C#项目,并选择“Windows服务”模板。 然后,在你的服务类中,你可以使用`System.Timers.Timer`类来执行定时任务。在服务的`OnStart`方法中初始化定时器,并设置间隔时间和要执行方法。在`OnStop`方法中停止定时器。 这是一个基本的示例代码: ```csharp using System; using System.ServiceProcess; using System.Timers; namespace YourNamespace { public partial class YourService : ServiceBase { private Timer timer; public YourService() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(); timer.Interval = 60000; // 1 minute in milliseconds timer.Elapsed += TimerElapsed; timer.Start(); } protected override void OnStop() { timer.Stop(); timer.Dispose(); } private void TimerElapsed(object sender, ElapsedEventArgs e) { // 执行你的定时任务 } } } ``` 请注意,上面的代码将每隔1分钟执行一次`TimerElapsed`方法。你可以根据需要更改间隔时间。 一旦你完成了代码编写,你可以将你的项目编译为一个执行文件,然后使用`installutil`命令行工具来安装和启动服务。例如,打开命令提示符,导航到你的可执行文件所在的文件夹,并运行以下命令: ``` installutil YourService.exe ``` 这将安装你的服务,并可以使用服务管理器启动、停止和管理它。 希望这可以帮助到你开始编写一个定时执行Windows服务!如有任何问题,欢迎继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值