一:编写一个HelloJob任务类,里面写要执行的任务
public class HelloJob implements Job{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//编写具体的业务逻辑
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间为:"+sdf.format(date));
System.out.println("hello");
}
}
二:写定时任务来进行调度
创建一个JobDetail实例,将该实例跟要执行的job类进行绑定
创建一个tigger实例,定义该job什么时候执行
创建Scheduler实例,定义什么job在什么时候执行以及如何执行
public class HelloScheduler {
public static void main(String[] args) throws SchedulerException{
//创建一个JobDetail实例,将该实例与HelloJob Class绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob","group1").build();
//创建一个tigger实例,定义该job立即执行,并且每隔两秒重复执行
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("myTrigger","group1")
.startNow()
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2).repeatForever())
.build();
//创建Scheduler实例
SchedulerFactory s = new StdSchedulerFactory();
Scheduler scheduler = s.getScheduler();
scheduler.start();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间为:"+sdf.format(date));
scheduler.scheduleJob(jobDetail,trigger);
}
}
网友评论