任务调度
Timer TimerTask
public class TimerTest {
public static void main(String[] args) {
Timer timer1 = new Timer();
timer1.schedule(new MyTask(), 1000,1000);
Calendar cal = new GregorianCalendar(2019,4,29,19,15,10);
timer1.schedule(new MyTask(),cal.getTime() , 200);
}
}
class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("hello timer");
}
}
QUARTZ
public class HelloJob implements Job {
public HelloJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("-------start---------");
System.out.println("Hello World! - " + new Date());
System.out.println("-------end---------");
}
}
public class QuartzTest {
public void run() throws Exception {
// 1、创建 Scheduler的工厂
SchedulerFactory sf = new StdSchedulerFactory();
//2、从工厂中获取调度器
Scheduler sched = sf.getScheduler();
// 3、创建JobDetail
JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();
// 时间
Date runTime = evenSecondDateAfterNow();
// 4、触发条件
//Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(5).withRepeatCount(3)).build();
// 5、注册任务和触发条件
sched.scheduleJob(job, trigger);
// 6、启动
sched.start();
try {
// 100秒后停止
Thread.sleep(100L * 1000L);
} catch (Exception e) {
}
sched.shutdown(true);
}
public static void main(String[] args) throws Exception {
QuartzTest example = new QuartzTest();
example.run();
}
}