在Window服務中應用Timer

來源:互聯網
上載者:User

在Windwo服務中應用Timer記的要把System.Windows.Forms.Timer timer1改成System.Timers.Timer timer1。事件使用timer1_Elapsed,而不是time1_Tick

 

  #region 組件設計器產生的程式碼

        /// <summary>
        /// 設計器支援所需的方法 - 不要
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.timer1 = new System.Timers.Timer();
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            //
            // myService
            //
            this.ServiceName = "myService";
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();

        }

        #endregion

        //private System.Windows.Forms.Timer timer1;
        private System.Timers.Timer timer1;
    }

 

 

 

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;

namespace myService
{
    public partial class myService : ServiceBase
    {
        public myService()
        {
            InitializeComponent();
           
        }

        protected override void OnStart(string[] args)
        {
            timer1.Enabled = true;
            timer1.Start();
        }

        protected override void OnPause()
        {
            timer1.Stop();
        }

        protected override void OnContinue()
        {
            timer1.Start();
        }

        protected override void OnStop()
        {
            timer1.Stop();
        }

        protected void exe()
        {
            SqlConnection con = new SqlConnection("server=PC-201104141904\\SQL2005;database=myDataBase;user id=sa;password=sasasa");
            string sql = "insert into tb_User(UserName,Password) values('name','password')";
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            exe();
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.