如何开发一个运行在windows系统服务器上的服务
第一步:vs2022创建一个windows服务项目
第二步:从工具箱拖拽出一个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.Threading.Tasks;
using System.Timers;namespace FlyBookDataProject
{public partial class Service1 : ServiceBase{private Timer timer;public Service1(){InitializeComponent();}protected override void OnStart(string[] args){timer = new Timer(60000); // 60秒间隔timer.Elapsed += OnTimedEvent;timer.AutoReset = true; // 设置为true表示定时器在触发后会自动重置并重新开始计时timer.Enabled = true; // 启动定时器}protected override void OnStop(){timer.Stop();timer.Elapsed -= OnTimedEvent;timer.Dispose();}private async void OnTimedEvent(Object source, ElapsedEventArgs e){// 执行你的任务DateTime now = DateTime.Now;if (now.Hour == 8 && now.Minute == 42){writeTxtCls log = new writeTxtCls();log.writeTxtToFile("\r\n[" + System.DateTime.Now.ToString() + "]:开始执行任务");List<userinfo> list = new List<userinfo>();string sql = "select * from vw_QianDaoUserList_base";dynamic dt = Public.DB.SqlQueryable<dynamic>(sql).ToList();foreach (var item in dt){userinfo userinfo = new userinfo();userinfo.id = item.UserId;userinfo.ifqiandao = false;userinfo.dzcount = 0;userinfo.wrong1count = 0;userinfo.wrong2count = 0;userinfo.flag = 1;list.Add(userinfo);}int i = 1;while (true){foreach (var ss in list){int goon = 1;if (!ss.ifqiandao && ss.wrong1count < 2){int asd = Public.DoWork(ss.id);if (asd == 1){ss.ifqiandao = true;}else{ss.wrong1count++;}}else{goon++;}if (ss.dzcount < 5 && ss.wrong2count < 6){int asd = Public.DoWork1(ss.id);if (asd == 1){ss.dzcount++;}else{ss.wrong2count++;}}else{goon++;}if (goon == 3){ss.flag = 2;}}list.RemoveAll(it => it.flag == 2);if (list.Count == 0){log.writeTxtToFile("\r\n[" + System.DateTime.Now.ToString() + "]:任务执行完成");break;}log.writeTxtToFile("\r\n[" + System.DateTime.Now.ToString() + "]:执行第" + i + "次,当前状态:" + JsonConvert.SerializeObject(list));i++;await Task.Delay(60000);}}}private void timer1_Tick(object sender, EventArgs e){}}
}
第四步:
1、项目重新生成,在项目的bin/Debug下,如果生成了exe文件,比如 MyTimerService.exe
2、在服务器D盘下创建一个文件夹名为MyTimerService
3、将bin/Debug下的所有文件复制到D:/MyTimerService
4、将两个bat文件复制到C盘下,以管理员身份运行setup.bat
setup
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
installutil /u D:\MyTimerService\MyTimerService.exe
pause
unsetup
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
installutil D:\MyTimerService\MyTimerService.exe
pause