Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,可以用来创建简单或者复杂的定时任务,利用Quartz开发定时任务的步骤与Timer类
似。
利用Quartz开发定时任务是主要分为两个步骤:
1)创建定时任务类
示例代码:
package org.lzstone.action
public class LzstoneTimeTask implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException{
//执行的定时器任务
}
}
2)运行定时任务,运行定时任务分为两种方式:
2.1)程序直接启动,创建任务调度器及配置相应的任务计划
示例代码:
package org.lzstone.action;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
public class LzstoneMain{
private static Scheduler sched;
public static void run() throws Exception{
//创建LzstoneTimeTask的定时任务
JobDetail jobDetail = new JobDetail("lzstoneJob",sched.DEFAULT_GROUP,LzstoneTimeTask.class);
//目标 创建任务计划
CronTrigger trigger = new CronTrigger("lzstoneTrigger","lzstone","0 0 12 * * ?");
//0 0 12 * * ? 代表每天的中午12点触发
sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();
sched.scheduleJob(jobDetail,trigger);
sched.start();
}
//停止
public static void stop() throws Exception{
sched.shutdown();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
LzstoneMain.run();
}
}
本文介绍如何使用Quartz实现定时任务。首先展示了定时任务类的创建过程,然后详细解释了如何通过程序直接启动的方式运行定时任务,包括任务调度器的创建、任务计划的配置以及定时任务的具体启动和停止。
489

被折叠的 条评论
为什么被折叠?



