1.创建多线程类

   /// <summary>
/// 多线程
/// </summary>
public abstract class MuliThread<T>
{
/// <summary>
/// 线程
/// </summary>
private static readonly List<Thread> Threads = new List<Thread>();
/// <summary>
/// 日志
/// </summary>
private static readonly Log Log = new Log("Tasks");
private static readonly List<Func<bool>> ExitFuncs = new List<Func<bool>>(); #region 启动&停止 /// <summary>
/// 启动任务
/// </summary>
/// <param name="type">0:异步启动1:同步启动</param>
public static void Start(int type = )
{
typeof(T).GetConstructors().First().Invoke(null);
new Thread(Begin).Start(type);
}
/// <summary>
/// 启动
/// </summary>
private static void Begin(object type)
{
var typeName = typeof(T).Name;
var threads = Threads.Where(a => a.Name.StartsWith(typeName)).ToArray();
foreach (var thread in threads)
{
if (!thread.IsBackground)
{
thread.IsBackground = true;
}
var times = ;
while (thread.ThreadState == (ThreadState.Background | ThreadState.Unstarted) && times < )
{
try
{
thread.Start();
}
catch (Exception e)
{
times++;
Log.Error(e.Message + e.StackTrace);
}
Thread.Sleep();
}
} Log.Info(typeName, "启动成功,共启动个{0}线程".Formats(threads.Length));
if (type.ConvertTo() != ) return;
Thread.Sleep();
foreach (var thread in threads)
{
try
{
thread.Join();
}
catch (Exception e)
{
Log.Error(e.Message + e.StackTrace);
}
}
} private static void End()
{
var typeName = typeof(T).Name;
try
{
Log.Info(typeName, "共 {0} 个线程".Formats(Threads.Count)); var threads = Threads.Where(a => a.Name.StartsWith(typeName)).ToArray();
while (threads.Count(a => a != null && a.IsAlive) > )
{
foreach (var thread in threads)
{
if (thread.IsAlive)
{
thread.Abort();
Log.Info(typeName, "正在终止线程 {0}".Formats(thread.ManagedThreadId));
}
} Log.Info(typeName, "剩余 {0} 个未终止".Formats(threads.Count(a => a != null && a.IsAlive))); Thread.Sleep();
} Log.Info(typeName, "线程全部正常停止");
}
catch (Exception e)
{
Log.Error(typeName, "{0} {1}".Formats(e.Message, e.StackTrace));
}
} /// <summary>
/// 停止任务
/// </summary>
public static void Exit()
{
foreach (var func in ExitFuncs)
{
func();
}
new Thread(End).Start();
} #endregion protected static void LogDebug(string log)
{
Log.Debug(typeof(T).Name, log);
}
protected static void LogInfo(string log)
{
Log.Info(typeof(T).Name, log);
}
protected static void LogTicketInfo(string log)
{
Log.TicketInfo(typeof(T).Name, log);
}
protected static void LogTicketError(string log)
{
Log.TicketError(typeof(T).Name, log);
}
protected static void LogWarn(string log)
{
Log.Warn(typeof(T).Name, log);
} protected static void LogError(string log)
{
Log.Error(typeof(T).Name, log);
} /// <summary>
/// 添加任务
/// </summary>
protected static void AddTask(ThreadStart threadStart)
{
lock (Threads)
{
Threads.Add(new Thread(threadStart) { Name = typeof(T).Name });
}
}
/// <summary>
/// 批量添加任务
/// </summary>
protected static void AddTasks(IEnumerable<ThreadStart> threadStarts)
{
foreach (var threadStart in threadStarts)
{
AddTask(threadStart);
}
} /// <summary>
/// 添加退出时执行任务
/// </summary>
protected static void AddExitCall(Func<bool> func)
{
ExitFuncs.Add(func);
}
}

2. 创建服务调用类

  public class AutoAddIssues : MuliThread<AutoAddIssues>
{
public AutoAddIssues()
{
StartAddIssue();
}
private static void StartAddIssue()
{
AddTask(AddIssueRun);
AddTask(ExcCurentStatus);
AddTask(OpenStart);
}
private static void ExcCurentStatus()
{
try
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = ;
timer.Elapsed += timer_Elapsed;
timer.AutoReset = true;
timer.Start();
}
catch (Exception ex)
{
new Log("ExcCurentStatus").Error(string.Format("Szpl.SSQAutoService.Task Start Error:{0}", ex.ToString()));
return;
}
new Log("ExcCurentStatus").Info(string.Format("Szpl.SSQAutoService.Task Start ....."));
} static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
DateTime dt1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, , , );
DateTime dt2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, , , );
TimeSpan ts1 = dt1.Subtract(DateTime.Now);
TimeSpan ts2 = dt2.Subtract(DateTime.Now);
if (ts1.TotalSeconds < && ts2.TotalSeconds > )
{
(sender as System.Timers.Timer).Interval = * * * ;
UpdateIssueStatus.Execute();
new Log("ExcCurentStatus").Info(string.Format("Szpl.SSQAutoService.Task Start Time : {0},Does not exist", DateTime.Now));
}
else
{
(sender as System.Timers.Timer).Interval = ;
}
}
catch (Exception ex)
{
new Log("ExcCurentStatus").Info(string.Format("Error:{0}", ex.ToString()));
}
} public static void OpenStart()
{
try
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = ;
timer.Elapsed += timer_Elapsed_OpenStart;
timer.AutoReset = true;
timer.Start();
}
catch (Exception ex)
{
new Log("ExcCurentStatus").Error(string.Format("Szpl.SSQAutoService.Task Start Error:{0}", ex.ToString()));
return;
}
new Log("ExcCurentStatus").Info(string.Format("Szpl.SSQAutoService.Task Start ....."));
}
static void timer_Elapsed_OpenStart(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime dt1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, , , );
DateTime dt2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, , , );
TimeSpan ts1 = dt1.Subtract(DateTime.Now);
TimeSpan ts2 = dt2.Subtract(DateTime.Now);
if (ts1.TotalSeconds < && ts2.TotalSeconds > )
{
List<T_Issues> Issues = T_Issues.Select(" Id,RIGHT(Name,5) Name,LotteryId ", " CurrentStatus=3 and IsOpened=0 and OpenLotteryNnumber='' ");
if (Issues == null || Issues.Count <= )
{
(sender as System.Timers.Timer).Interval = ;
return;
}
else
{
UpdateIssueStatus.GetAgent("", "ssq", Issues[].Name.Trim(), Issues[].Id);
} Issues = T_Issues.Select(" Id,Name,LotteryId,OpenLotteryNnumber ", " CurrentStatus=3 and OpenLotteryNnumber<>'' and IsOpened=0 ");
if (Issues.Count <= )
{
(sender as System.Timers.Timer).Interval = ;
new Log("OpenStart").Warn("OpenStart -->> select issues < 0 ");
return;
} (sender as System.Timers.Timer).Interval = * * * ; AutoOpened.Execute(Issues); }
else
{
(sender as System.Timers.Timer).Interval = ;
}
} private static void AddIssueRun()
{
int sleepTime = ;
while (true)
{
try
{
SelectIssue(ref sleepTime);
}
catch (Exception ex)
{
LogError("添加期号失败 {0} {1}".Formats(ex.Message, ex.StackTrace));
} System.Threading.Thread.Sleep(sleepTime);
}
}
private static void SelectIssue(ref int sleepTime)
{
try
{
string strSql = @"SELECT LotteryID,Name,StartTime,EndTime FROM T_Issues WHERE ID IN(
SELECT ID FROM (
SELECT MAX(ID) AS ID,LotteryID,(SELECT COUNT(1) FROM T_Issues WHERE EndTime>GETDATE() AND LotteryID = a.LotteryID) AS Num FROM T_Issues a
WHERE a.LotteryID=5 GROUP BY a.LotteryID) t WHERE Num<50)"; List<T_Issues> list = Sql.Select<T_Issues>(strSql);
if (list == null)
{
LogError("读取SSQ数据查询失败");
return;
} if (list.Count == )
{
sleepTime = ;
} foreach (T_Issues Issues in list)
{
AddIssues(Issues);
} }
catch (Exception ex)
{
LogError("SSQ Mathod SelectIssus Error {0}".Formats(ex.Message));
}
}
private static void AddIssues(T_Issues Issues)
{
var lotId = Issues.LotteryId;
var lastIssueName = Issues.Name;
var lastIssueStart = Issues.StartTime;
var lastIssueEndTime = Issues.EndTime; var issuePre = long.Parse(lastIssueName.Substring(, lastIssueName.Length - ));
var issueName = long.Parse(lastIssueName.Substring(lastIssueName.Length - ));
var newStart = new DateTime(lastIssueEndTime.Year, lastIssueEndTime.Month, lastIssueEndTime.Day, lastIssueStart.Hour, lastIssueStart.Minute, lastIssueStart.Second); var newEnd = lastIssueEndTime;
do
{
newEnd = newEnd.AddDays();
}
while (!IsCanAdd(lotId, newEnd)); if (lastIssueEndTime.Year != newEnd.Year)
{
issuePre = newEnd.Year;
issueName = ;
}
else
{
issueName++;
} Issues.LotteryId = lotId;
Issues.Name = issuePre + issueName.ToString().PadLeft(, '');
Issues.StartTime = newStart;
Issues.EndTime = newEnd; var newId = Issues.InsertId("LotteryID={0} AND Name={1}".Formats(Issues.LotteryId, Issues.Name));
if (newId < )
{
LogError("添加期号错误{0} {1} {2} {3}".Formats(Issues.LotteryId, Issues.Name, Issues.StartTime, Issues.EndTime));
}
}
private static bool IsCanAdd(long lotid, DateTime day)
{
switch (lotid)
{
case :
if (day.DayOfWeek == DayOfWeek.Tuesday || day.DayOfWeek == DayOfWeek.Friday || day.DayOfWeek == DayOfWeek.Sunday)
return true;
break;
case :
if (day.DayOfWeek == DayOfWeek.Tuesday || day.DayOfWeek == DayOfWeek.Thursday || day.DayOfWeek == DayOfWeek.Sunday)
return true;
break;
case :
if (day.DayOfWeek == DayOfWeek.Monday || day.DayOfWeek == DayOfWeek.Wednesday || day.DayOfWeek == DayOfWeek.Friday)
return true;
break;
case :
if (day.DayOfWeek == DayOfWeek.Monday || day.DayOfWeek == DayOfWeek.Wednesday || day.DayOfWeek == DayOfWeek.Saturday)
return true;
break;
default:
break;
}
return false;
}
}

3.必要属性配置

4. 项目框架结构

Windows服务定时执行任务的更多相关文章

  1. Windows服务定时执行方式

    采用System.Timers.Timer 间隔固定时间执行 方式一:间隔固定的时间执行一次,关键代码: protected override void OnStart(string[] args) ...

  2. js replace 全局替换 以表单的方式提交参数 判断是否为ie浏览器 将jquery.qqFace.js表情转换成微信的字符码 手机端省市区联动 新字体引用本地运行可以获得,放到服务器上报404 C#提取html中的汉字 MVC几种找不到资源的解决方式 使用Windows服务定时去执行一个方法的三种方式

    js replace 全局替换   js 的replace 默认替换只替换第一个匹配的字符,如果字符串有超过两个以上的对应字符就无法进行替换,这时候就要进行一点操作,进行全部替换. <scrip ...

  3. vs 2010创建Windows服务定时timer程序

    vs 2010创建Windows服务定时timer程序: 版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处:  http://www.cnblogs.com/2186009311CFF/p/ ...

  4. windows每天定时执行脚本

     windows每天定时执行脚本 这里说的定时器就是Windows下的任务计划,当时遇到的坑正好总结一下,因为Windows10的定时器去执行脚本当时试了好多遍,都是没有成功,后来通过自己的观察发现是 ...

  5. 使用ASP.NET实现Windows Service定时执行任务

    转载http://blog.csdn.net/yanghua_kobe/article/details/6937816 我们怎样才能在服务器上使用asp.net定时执行任务而不需要安装windows ...

  6. 使用C#开发windows服务定时发消息到钉钉群_群组简单消息

    前言:本提醒服务,是由C#语言开发的,主要由windows服务项目和winform项目组成,运行服务可实现功能:向钉钉自定义机器人群组里,定时,定次,推送多个自定义消息内容,并实现主要功能的日志记录. ...

  7. C#使用windows服务定时调用api接口

    使用VS创建windows服务项目: 创建好项目  会出现一个设计界面 右键弹出对话框 选择添加安装程序 名字什么的自己可以改: 项目目录: 打开项目中的ProjectInstaller.Design ...

  8. 使用Windows服务定时去执行一个方法的三种方式

    方式一:使用System.Timers.Timer定时器 public partial class Service1 : ServiceBase { private UnitOfWork unitOf ...

  9. windows上定时执行php文件

    <?php $fp = fopen("E:/wwwroot/test/plan.txt", "w+"); fwrite($fp, date("Y ...

随机推荐

  1. android volley http请求框架

    2015年11月6日 14:35:19 注意: 1.安卓官方的volley在google的codesource上, 在github上有他的镜像android-volley, 并解决了官方的一部分bug ...

  2. ACM/ICPC 之 DFS求解欧拉回路+打表(POJ1392)

    本题可以通过全部n位二进制数作点,而后可按照某点A的末位数与某点B的首位数相等来建立A->B有向边,以此构图,改有向图则是一个有向欧拉回路,以下我利用DFS暴力求解该欧拉回路得到的字典序最小的路 ...

  3. 多国语言文档识别 ABBYY FineReader Corporate v12.0.101.388.7z 绿色破解版

    ABBYY 是一家俄罗斯软件公司,在文档识别,数据捕获和语言技术的开发中居世界领先地位.其获奖产品 FineReader OCR 软件可以把静态纸文件和 PDF 文件转换成可管理的电子数据,可以大大节 ...

  4. ABAP 销售范围

    *&---------------------------------------------------------------------* *& Report  ZSDR008 ...

  5. ABAP 内表的行列转换-发货通知单-打印到Excel里-NEW-(以运单号为单位显示ALV然后保存输出)

    *********************************************************************** * Title           : ZSDF003  ...

  6. Bestcoder13 1003.Find Sequence(hdu 5064) 解题报告

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5064 题目意思:给出n个数:a1, a2, ..., an,然后需要从中找出一个最长的序列 b1, b ...

  7. 【轮子】发现一个效果丰富酷炫的Android动画库

    没有什么比发现一个好轮子更让人开心的了. 这个库分分钟提高交互体验 :AndroidViewAnimations 一张图说明一切 配置和使用也相当简单 GitHub地址

  8. sql 查询表的所有详细信息

    SELECT (case when a.colorder=1 then d.name else '' end) as 表名,--如果表名相同就返回空 a.colorder as 字段序号, a.nam ...

  9. 模拟赛1029d2

    [问题描述]祖玛是一款曾经风靡全球的游戏,其玩法是:在一条轨道上初始排列着若干个彩色珠子,其中任意三个相邻的珠子不会完全同色.此后,你可以发射珠子到轨道上并加入原有序列中.一旦有三个或更多同色的珠子变 ...

  10. NYOJ题目893十字架

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAsYAAAQRCAIAAACl4dlPAAAgAElEQVR4nO3dO1Ljyv834P8myFkIsR