[원문] : http://www.dotnetspider.com/resources/37688-A-Simple-Window-Service-With-Timer.aspx
visual studio c# 2010,
C#을 이용한 윈도우 서비스 개발 , 타이머를 이용한 실시간 처리 에 활용할 만한 아주 기본적인소스 ,
참고-> system.Window.Form 에 있는 timer는 사용 할 수 없습니다.
이것 때문에 엄청 나게 삽질함 , System.Timer를 사용하면됨
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;
using System.Configuration;
using System.Timers;
namespace TestWindowsService
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer timer = null;
public Service1()
{
double interval = 100000;
InitializeComponent();
timer = new System.Timers.Timer(interval);
timer.Elapsed += new ElapsedEventHandler(this.ServiceTimer_Tick);
}
protected override void OnStart(string[] args)
{
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}
protected override void OnStop()
{
timer.AutoReset = false;
timer.Enabled = false;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
this.timer.Stop();
SqlCommand MyCmd = new SqlCommand();
DataSet MyDs = new DataSet();
SqlConnection MyCon = new SqlConnection(ConfigurationSettings.AppSettings["MyCon"].ToString());
try
{
MyCmd.Connection = MyCon;
MyCmd.CommandText = "insert into CustOrder (date,price,customer) values ('" + DateTime.Now.ToShortDateString() + "','120','vivek sharma')";
MyCon.Open();
MyCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
MyCon.Close();
MyCmd.Dispose();
}
this.timer.Start();
}
protected override void OnPause()
{
this.timer.Stop();
}
protected override void OnContinue()
{
this.timer.Start();
}
}
}
- Posted
- Filed under C#