WinService簡單運用

来源:互联网 发布:在淘宝买主机可靠吗 编辑:程序博客网 时间:2024/05/02 00:35

1.Service1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;

namespace TestWinService
{   
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer t = new System.Timers.Timer();
        TestThead sub = new TestThead();//new控制線程對象
        string Strtime1begin = "06:00";//6點開始
        string Strtime1end = "23:00";//11點結束
        public Service1()
        {
            InitializeComponent();
            t.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            t.Interval = 60000;//1000毫秒
        }

        protected override void OnStart(string[] args)
        {
            t.Enabled = true;
            log("Start……");
            // TODO: 在此处添加代码以启动服务。
        }      

        protected override void OnStop()
        {
            t.Enabled = false;
            if (sub != null)
                sub.Dispose();
            if (t != null)
                t.Dispose();
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            DateTime time1begin = DateTime.Parse(Strtime1begin);
            DateTime time1end = DateTime.Parse(Strtime1end);

            if ((DateTime.Now > time1begin) && (DateTime.Now < time1end))
            {
                //在特定时间内

                if (sub.IsStopped == true || sub.IsDone == false)
                {
                    sub.Start();
                    log(" begin");
                }
            }
        }

        private void log(string logtxt)
        {
            string path = @"d:/test.txt";


            FileInfo f = new FileInfo(path);

            if (!f.Exists)
                f.CreateText().Close();


            StreamWriter sw = File.AppendText(@"d:/test.txt");


            sw.WriteLine(DateTime.Now.ToString() + "," + logtxt);

            sw.Flush();

            sw.Close();
            sw.Dispose();
            GC.Collect();
        }
    }
}

2.TestWinService.cs:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.OracleClient;
using System.Data;
using System.Threading;
using System.IO;


namespace TestWinService
{
       
    class TestThead
    {
        private const string MgConStr = "Data Source = ORCL_EIP;Persist Security Info = True; User ID = mguser;Password = mgpassword;Unicode=True";

        private Thread thdSubThread = null;

        private Mutex mUnique = new Mutex();

        private bool blnIsStopped;//是否停止狀態

        private bool blnSuspended;//是否挂起

        private bool blnStarted;//是否開始

        private bool blnDone;//是否正常做完

        public bool IsStopped
        {

            get { return blnIsStopped; }

        }

        public bool IsSuspended
        {

            get { return blnSuspended; }

        }

        public bool IsDone
        {

            get { return blnDone; }

        }

        public TestThead()
        {

            blnIsStopped = true;

            blnSuspended = false;

            blnStarted = false;

            blnDone = false;


        }

        public void Start()
        {
            if (!blnStarted)
            {

                thdSubThread = new Thread(new ThreadStart(ThreadFun));
                thdSubThread.IsBackground = true;

                blnIsStopped = false;

                blnStarted = true;

                thdSubThread.Start();

            }

        }

        private void ThreadFun()
        {
            ArrayList sqls = new ArrayList();//存放導入sql語句
            string y = System.DateTime.Now.Year.ToString();//獲取導入當天的日期
            string d = System.DateTime.Now.Day.ToString();
            string m = System.DateTime.Now.Month.ToString();
            if (m.Length == 1)
            {
                m = "0" + m;
            }
            if (d.Length == 1)
            {
                d = "0" + d;
            }
            string date = y + "/" + m + "/" + d;
            DataSet ds = new DataSet();
            string sql = "select ID,NAME,CREATE_DATE from TESTWIN_1 where to_char(CREATE_DATE,'yyyy/mm/dd')='" + date + "'";           
            string tmp = string.Empty;
            OracleConnection con = new OracleConnection(MgConStr);
            try
            {
                con.Open();
                OracleDataAdapter da = new OracleDataAdapter(sql, con);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                //終止線程
                ErrorStop("提取數據:" + ex.ToString());
                GC.Collect();
                Dispose();
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        //使用merge函數導入
                        tmp = "merge into TESTWIN_2 TB using(select " + dr["ID"].ToString().Trim() + " as ID from dual) TA on (TB.ID=TA.ID) when matched then " +
                            "update set NAME='" + dr["NAME"].ToString().Trim() + "',CREATE_DATE=to_date('" + Convert.ToDateTime(dr["CREATE_DATE"].ToString().Trim()).ToString("yyyy-MM-dd") + "','yyyy/MM/dd') when not matched then " +
                            "insert(ID,NAME,CREATE_DATE) values(" + dr["ID"].ToString().Trim() + ",'" + dr["NAME"].ToString().Trim() + "',to_date('" + Convert.ToDateTime(dr["CREATE_DATE"].ToString().Trim()).ToString("yyyy-MM-dd") + "','yyyy/MM/dd'))";
                        sqls.Add(tmp);
                    }
                }
                else
                {
                    ErrorStop("null");
                }
            }
            else
            {
                ErrorStop("null");
            }
            //插入數據
            if (sqls.Count > 0)
            {
                OracleConnection con2 = new OracleConnection(MgConStr);
                con2.Open();
                OracleTransaction ot = con2.BeginTransaction();
                OracleCommand cmd = new OracleCommand();
                try
                {
                    cmd.Connection = con2;
                    cmd.Transaction = ot;
                    for (int i = 0; i < sqls.Count; i++)
                    {
                        tmp = sqls[i].ToString();
                        cmd.CommandText = tmp;
                        cmd.ExecuteNonQuery();
                    }
                    ot.Commit();
                }
                catch (Exception ex)
                {
                    ot.Rollback();
                    ErrorStop("導入數據:" + ex.ToString() + tmp);
                    GC.Collect();
                    Dispose();
                }
                finally
                {
                    cmd.Dispose();
                    con2.Close();
                    con2.Dispose();
                    GC.Collect();
                    Dispose();
                }
            }
            else
            {
                GC.Collect();
                Dispose();
            }
        }

        public void ErrorStop(string mes)
        {
            if (blnStarted)
            {
                if (blnSuspended)

                    Resume();

                blnStarted = false;

                blnIsStopped = true;
                log(mes);
                ////thdSubThread.Join();
                thdSubThread.Abort();

                blnDone = false;


            }

        }

        public void Dispose()
        {

            // TODO:  Add clsSubThread.Dispose implementation

            Stop();//Stop thread first

            GC.SuppressFinalize(this);

        }

        public void Resume()
        {

            if (blnStarted && blnSuspended)
            {

                blnSuspended = false;

                mUnique.ReleaseMutex();

            }

        }   

        public void Stop()
        {

            if (blnStarted)
            {

                if (blnSuspended)

                    Resume();

 

                blnStarted = false;

                blnIsStopped = true;

                //thdSubThread.Join();
                thdSubThread.Abort();


                blnDone = true;

            }

        }

        private void log(string logtxt)
        {
            string path = @"d:/test.txt";

            FileInfo f = new FileInfo(path);

            if (!f.Exists)
                f.CreateText().Close();

            StreamWriter sw = File.AppendText(@"d:/test.txt");


            sw.WriteLine(DateTime.Now.ToString() + "," + logtxt);

            sw.Flush();
            sw.Close();
            sw.Dispose();
            GC.Collect();
        }

    }

 


}
3.

創建安裝程序:

返回到Service

的設計界面,右擊選擇“添加安裝程序”,選擇完之後會自動新增ProjectInstaller.cs類,

 

4.創建安裝程序

TestWinService添加到安裝程序中,然後選擇TestWinService 做為輸出項目,

點擊“確定”,進入下一步,

跳出此界面,

選擇“應用程序文件夾”點擊“確定”,最後生成項目,完成安裝程序的製作。

安裝Windows Service

運行生成的安裝包,默認進入下一步,即可完成安裝。

安裝完成后進入Windows服務管理器啟動剛剛安裝的服務即可。

 

原创粉丝点击