定时任务 Wpf.Quartz.Demo.1
Quartz 是个开源的作业调度框架.
安装:Install-Package Quartz
官网文档地址:https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/using-quartz.html
资源比较多,这里不做介绍。
任务设置有两种方式:SimpleTrigger和CronTrigger,如下:
var trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartAt(myStartTime) // some Date
.ForJob("job1", "group1") // identify job with name, group strings
var trigger = TriggerBuilder.Create()
.WithIdentity("trigger3", "group1")
.WithCronSchedule("0 0/2 8-17 * * ?")
.ForJob("myJob", "group1")
.Build();
第二种的在线表达式生成工具网址:http://cron.qqe2.com/
在这里写个控制台的Demo来看看定时任务的效果,我们先简单的封装一下任务的启动和停止等,主要代码如下:
public class QuartzHelper
{
private static QuartzHelper instance = new QuartzHelper(); public static QuartzHelper Instance
{
get
{
if (instance == null)
{
instance = new QuartzHelper();
}
return instance;
}
} private const string JOB_GROUP_NAME = "JOB_GROUP_NAME";
private const string TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME"; /// <summary>
/// 程序调度
/// </summary>
private static IScheduler _scheduler; /// <summary>
/// 初始化任务调度对象
/// </summary>
private QuartzHelper()
{ } /// <summary>
/// 时间间隔执行任务
/// </summary>
/// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
/// <param name="seconds">时间间隔(单位:毫秒)</param>
public async Task StartJobExecuteInterval<T>(int seconds, string jobName = null, string jobGroupName = null, string triggerName = null, string triggerGroupName = null) where T : IJob
{
await InitJobs(); //IJobDetail job = JobBuilder.Create<T>().WithIdentity("job1", "group1").Build();
IJobDetail job = JobBuilder.Create<T>().Build(); ITrigger trigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever())
.Build(); await _scheduler.ScheduleJob(job, trigger); await _scheduler.Start();
} /// <summary>
/// 指定时间执行任务
/// </summary>
/// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
/// <param name="cronExpression">cron表达式,即指定时间点的表达式</param>
public async Task<TriggerState> StartJobExecuteByCron<T>(string cronExpression, string jobName, object para = null, DateTime? startTime = null, DateTime? endTime = null, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME) where T : IJob
{
await InitJobs(); IJobDetail job = JobBuilder.Create<T>()
.WithIdentity(jobName, jobGroupName)
.Build();
job.JobDataMap.Put("Runner", para); ITrigger trigger;
if (startTime == null && endTime == null)
{
trigger = TriggerBuilder.Create()
.WithIdentity(triggerName ?? jobName, triggerGroupName)
.WithCronSchedule(cronExpression)
.Build();
}
else if (startTime != null && endTime == null)
{
trigger = TriggerBuilder.Create()
.WithIdentity(triggerName ?? jobName, triggerGroupName)
.StartAt(CronHelper.DateTime2DateTimeOffset(startTime.Value))
.WithCronSchedule(cronExpression)
.Build();
}
else if (startTime == null && endTime != null)
{
trigger = TriggerBuilder.Create()
.WithIdentity(triggerName ?? jobName, triggerGroupName)
.EndAt(CronHelper.DateTime2DateTimeOffset(endTime.Value))
.WithCronSchedule(cronExpression)
.Build();
}
else
{
trigger = TriggerBuilder.Create()
.WithIdentity(triggerName ?? jobName, triggerGroupName)
.StartAt(CronHelper.DateTime2DateTimeOffset(startTime.Value))
.EndAt(CronHelper.DateTime2DateTimeOffset(endTime.Value))
.WithCronSchedule(cronExpression)
.Build();
} await _scheduler.ScheduleJob(job, trigger); await _scheduler.Start(); return await _scheduler.GetTriggerState(trigger.Key);
} public async Task<TriggerState> ModifyJobTime(string cronExpression, string jobName, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME)
{
IJobDetail job;
ITrigger trigger; job = await _scheduler.GetJobDetail(new JobKey(jobName, jobGroupName));
trigger = await _scheduler.GetTrigger(new TriggerKey(triggerName ?? jobName, triggerGroupName));
if (job == null || trigger == null)
{
return TriggerState.None;
} await _scheduler.UnscheduleJob(trigger.Key); trigger = TriggerBuilder.Create()
.WithIdentity(trigger.Key.Name, trigger.Key.Group)
.WithCronSchedule(cronExpression)
.Build(); await _scheduler.ScheduleJob(job, trigger); return await _scheduler.GetTriggerState(trigger.Key);
} public async Task<TriggerState> RemoveJob(string jobName, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME)
{ IJobDetail job;
ITrigger trigger; job = await _scheduler.GetJobDetail(new JobKey(jobName, jobGroupName));
trigger = await _scheduler.GetTrigger(new TriggerKey(triggerName ?? jobName, triggerGroupName));
if (job == null || trigger == null)
{
return TriggerState.None;
} await _scheduler.UnscheduleJob(trigger.Key);
await _scheduler.DeleteJob(job.Key); return await _scheduler.GetTriggerState(trigger.Key);
} public async Task<TriggerState> PauseJob(string jobName, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME)
{
IJobDetail job;
ITrigger trigger; job = await _scheduler.GetJobDetail(new JobKey(jobName, jobGroupName));
trigger = await _scheduler.GetTrigger(new TriggerKey(triggerName ?? jobName, triggerGroupName));
if (job == null || trigger == null)
{
return TriggerState.None;
} await _scheduler.PauseJob(job.Key); return await _scheduler.GetTriggerState(trigger.Key);
} public async Task<TriggerState> ResumeJob(string jobName, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME)
{
IJobDetail job;
ITrigger trigger; job = await _scheduler.GetJobDetail(new JobKey(jobName, jobGroupName));
trigger = await _scheduler.GetTrigger(new TriggerKey(triggerName ?? jobName, triggerGroupName));
if (job == null || trigger == null)
{
return TriggerState.None;
} await _scheduler.ResumeJob(job.Key); return await _scheduler.GetTriggerState(trigger.Key);
} public async Task<TriggerState> GetJobState(string jobName, string jobGroupName = JOB_GROUP_NAME, string triggerName = null, string triggerGroupName = TRIGGER_GROUP_NAME)
{
IJobDetail job;
ITrigger trigger; job = await _scheduler.GetJobDetail(new JobKey(jobName, jobGroupName));
trigger = await _scheduler.GetTrigger(new TriggerKey(triggerName ?? jobName, triggerGroupName));
if (job == null || trigger == null)
{
return TriggerState.None;
}
return await _scheduler.GetTriggerState(trigger.Key);
} public async Task InitJobs()
{
if (_scheduler != null)
{
return;
} //配置文件的方式,配置quartz实例
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = await schedulerFactory.GetScheduler();
} public async Task StartJobs()
{
if (_scheduler != null)
{
await _scheduler.Start(); return;
} //配置文件的方式,配置quartz实例
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = await schedulerFactory.GetScheduler();
await _scheduler.Start();
} public void StandbyJobs()
{
try
{
if (_scheduler == null) return;
if (!_scheduler.InStandbyMode)
{
_scheduler.Standby();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} public void RestartJobs()
{
_scheduler.Shutdown();
_scheduler.Start();
} public DateTime[] GetNextRunTime(string cronExpression, DateTime? startTime,DateTime? endTime, int number = )
{
try
{
ITrigger trigger = null;
if (startTime == null && endTime == null)
{
trigger = TriggerBuilder.Create()
.WithCronSchedule(cronExpression)
.Build();
}
else if (startTime != null && endTime == null)
{
trigger = TriggerBuilder.Create()
.StartAt(CronHelper.DateTime2DateTimeOffset(startTime.Value))
.WithCronSchedule(cronExpression)
.Build();
}
else if (startTime == null && endTime != null)
{
trigger = TriggerBuilder.Create()
.EndAt(CronHelper.DateTime2DateTimeOffset(endTime.Value))
.WithCronSchedule(cronExpression)
.Build();
}
else
{
trigger = TriggerBuilder.Create()
.StartAt(CronHelper.DateTime2DateTimeOffset(startTime.Value))
.EndAt(CronHelper.DateTime2DateTimeOffset(endTime.Value))
.WithCronSchedule(cronExpression)
.Build();
} IList<DateTimeOffset> dates = TriggerUtils.ComputeFireTimes(trigger as IOperableTrigger, null, number).ToList();
if (dates != null && dates.Count > )
{
return dates.Select(p => TimeZoneInfo.ConvertTimeFromUtc(p.DateTime, TimeZoneInfo.Local)).ToArray();
}
}
catch (Exception ex)
{ }
return null;
}
}
执行一个每5s执行一次的例子如下:
var TriggerState = await QuartzHelper.Instance.StartJobExecuteByCron<HelloJob>("0/5 * * * * ?", "测试1");
代码下载地址如下:https://pan.baidu.com/s/1W1UwoFPgyfo_ETDpHeEGsg
定时任务 Wpf.Quartz.Demo.1的更多相关文章
- 定时任务 Wpf.Quartz.Demo.4
本文继续介绍定时任务 Wpf.Quartz.Demo.3的一些小细节, 代码也请前往第3节下载. 1.RichTextBox右键菜单 <RichTextBox.ContextMenu> ...
- 定时任务 Wpf.Quartz.Demo.2
定时任务 Wpf.Quartz.Demo.1已经能运行了,本节开始用wpf搭界面. 准备工作: 1.界面选择MahApp.Metro 在App.xaml添加资源 <Application.Res ...
- 定时任务 Wpf.Quartz.Demo.5 (升级版)
老规矩:先把全部源码上传,见本文底部. 相对于Demo3的区别,就是能自动加载继承了IJob的任务,任务主体程序分离. 在exe执行文件的同级下建一个MyJobs的文件夹,每次会自动扫描该文件夹下的J ...
- 定时任务 Wpf.Quartz.Demo.3
先把全部源码上传,只是一个Demo,希望大家指点一下不足之处,见本文底部. 1.设置界面 2.详情页面 好了,现在慢慢叙述里面的一些方法. 3.实现拷贝的方法: (1) public static v ...
- [转][JAVA]定时任务之-Quartz使用篇
[BAT][JAVA]定时任务之-Quartz使用篇 定时任务之-Quartz使用篇 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与 ...
- Spring整合quartz2.2.3总结,quartz动态定时任务,Quartz定时任务集群配置
Spring整合quartz2.2.3总结,quartz动态定时任务,Quartz定时任务集群配置 >>>>>>>>>>>>&g ...
- 震惊!Windows Service服务和定时任务框架quartz之间原来是这种关系……
过场CG: 接到公司领导的文件指示,“小熊”需要在6月底去海外执行一个行动代号为[定时任务]的营救计划,这个计划关系到公司某个项目的生死(数据安全漏洞),作战部拟定两个作战方案: 方案一:使用务定 ...
- SpringBoot定时任务 - 集成quartz实现定时任务(单实例和分布式两种方式)
最为常用定时任务框架是Quartz,并且Spring也集成了Quartz的框架,Quartz不仅支持单实例方式还支持分布式方式.本文主要介绍Quartz,基础的Quartz的集成案例本,以及实现基于数 ...
- Spring 整合 Quartz 实现动态定时任务(附demo)
最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能也不够强大.在考虑之后,决定整合更为专业的Quartz来实现定时任务功能. 普通定时任务 首先 ...
随机推荐
- NOIP水题测试(2017082501)
日常水题测试又来了! 以后答案都以单题形式公布. 下面看今天的水题: 时间限制:5小时 题目一:无法形容的水 题目二:比上一题还水 题目三:一元三次方程求解 题目四:单词接龙 题目五:统计单词个数 题 ...
- Vbs脚本简单使用
之前在做项目时用到了一点vbs脚本,记录下. C++程序调用vbs脚本 System(vbs路径 参数); //空格隔开 Vbs脚本 '''''Vbs脚本解析参数 Set objArgs = Wscr ...
- hdu-4300(字符串hash)
题目链接:传送门 参考文章:传送门 思路: (1)对字符串进行翻译,求出s1(未翻译),s2(已翻译)字符串,并分别对s1,s2进行hash操作. (2)比较s1的后x位和s2的前x位的hash值,求 ...
- python模块:pickle
"""Create portable serialized representations of Python objects. See module copyreg f ...
- centos6上安装jenkins
一.安装jdk 1.下载地址:https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html ...
- Day1-Python基础--数据类型
距离上次更新,已经一月有余.说明学习状态不好,且滞后严重.第二模块也滞后5周之多,可能学习方法不对,有点凌乱,导致写作业时思路还是打不开,再一个是练习的太少了吧,以后得多挤挤时间来了.目前到了这个年纪 ...
- Arria10中的OCT功能
OCT是什么? 串行(RS)和并行(RT) OCT 提供了 I/O 阻抗匹配和匹配性能.OCT 维持信号质量,节省电路板空 间,并降低外部组件成本. Arria 10 器件支持所有 FPGA 和 HP ...
- linux上安装Elasticsearch
搭建环境centos7及 首先通过工具上传tar包到/usr/local/mypackage/elasticsearch 解压tar包 解压后进入config目录,编辑配置文件 vi elastics ...
- Java理论学时第四节。课后作业。
请查看String.equals()方法的实现代码,注意学习其实现方法. public class StringEquals { public static void main(String[] ar ...
- noip第27课作业
1. 繁忙的都市 [问题描述] 城市C是一个非常繁忙的大都市,城市中的道路十分的拥挤,于是市长决定对其中的道路进行改造.城市C的道路是这样分布的:城市中有n个交叉路口,有些交叉路口之间有道路相连,两个 ...