1:创建一个Windows服务应用程序
2:我写了一下代码
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.Timers;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WindowsServiceDemo
{
public partial class Service1 : ServiceBase
{
Timer EventTimer;//事件计时器
int Times = 0;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
EventTimer = new System.Timers.Timer();
EventTimer.Interval = 1000;
EventTimer.Elapsed+=new System.Timers.ElapsedEventHandler(Timer_Event);
EventTimer.Enabled = true;
}
private void Timer_Event(object sender,ElapsedEventArgs e)
{
//自定义需求代码
Times++;
//连接数据库
string ConnectionString = ConfigurationManager.ConnectionStrings["WindowsServiceDemoConnectionStrings"].ConnectionString.ToString();
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
//数据库操作
string sql_Insert = "INSERT INTO VIP VALUES('"+Times+"程咬金','"+Times+"8661269572')";
SqlCommand cmd_Insert = new SqlCommand(sql_Insert,conn);
cmd_Insert.ExecuteNonQuery();
conn.Close();
}
protected override void OnStop()
{
this.EventTimer.Enabled = false;
}
}
}