Quartz实现定时任务实例

时间:2021-10-23 07:49:25

1首先实现Job接口,创建任务

public class HelloJob implements Job{

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDetail jobDetail
= context.getJobDetail();
String name
= jobDetail.getJobDataMap().getString("name");
System.out.println(name
+":"+new Date());
}
}

2实现具体定时任务

public class QuartzTest {

public static void main(String[] args) throws Exception {

JobDetail job
=newJob()
.ofType(HelloJob.
class) //引用Job Class
.withDescription("this is a test job") //任务描述
.build();

job.getJobDataMap().put(
"name", "mytimer"); //加入属性name到JobDataMap

//定义一个每秒执行一次的SimpleTrigger触发器
Trigger trigger=newTrigger()
.startNow()
.withIdentity(
"trigger")
.withSchedule(CronScheduleBuilder.cronSchedule(
"0/5 * * * * ?"))
.build();

//获取默认调度器
Scheduler sche=StdSchedulerFactory.getDefaultScheduler();
sche.scheduleJob(job, trigger);

sche.start();

System.in.read();
sche.shutdown();
}
}