java定時任務有三種:
- JDK自帶 :JDK自帶的Timer以及JDK1.5+ 新增的ScheduledExecutorService;?
- Quartz :簡單卻強大的JAVA作業調度框架?
- Spring3.0以後自帶的task :可以將它看成壹個輕量級的Quartz,而且使用起來比Quartz簡單許多;
代碼參考:
JDK 自帶的定時器實現
schedule(TimerTask task, Date time) 特定時間執行
public static void main(String[] args) {
for (int i = 0; i < 10; ++i) {
new Timer("timer - " + i).schedule(new TimerTask() {
@Override
public void run() {
println(Thread.currentThread().getName() + " run ");
}
}, new Date(System.currentTimeMillis() + 2000));
}
}
Quartz 定時器實現
2.1? 通過maven引入依賴(這裏主要介紹2.3.0) ?註意:shiro-scheduler中依賴的是1.x版本 ?如果同時使用會沖突
<!-- /artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
2.2?創建Job類
public class TestJob implements Job{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
println(Thread.currentThread().getName() + " test job begin " + DateUtil.getCurrentTimeStr());
}
}
2.3?調度任務
public static void main(String[] args) throws InterruptedException, SchedulerException {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// 開始
scheduler.start();
// job 唯壹標識 test.test-1
JobKey jobKey = new JobKey("test" , "test-1");
JobDetail jobDetail = JobBuilder.newJob(TestJob.class).withIdentity(jobKey).build();
Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("test" , "test")
// 延遲壹秒執行
.startAt(new Date(System.currentTimeMillis() + 1000))
// 每隔壹秒執行 並壹直重復
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
.build();
scheduler.scheduleJob(jobDetail , trigger);
Thread.sleep(5000);
// 刪除job
scheduler.deleteJob(jobKey);
}
3.Spring 相關的任務調度
3.1 配置文件實現
spring-schedule.xml
<task:scheduler id="myScheduler" pool-size="10" />
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="job" method="test" cron="0 * * * * ?"/>
</task:scheduled-tasks>
3.2註解實現
spring-schedule.xml
<task:scheduler id="myScheduler" pool-size="10" />
// 啟用註解
<task:annotation-driven scheduler="myScheduler"/>
@Component?
public class Task{ ?
@Scheduled(cron="0/5 * *? * * ? ")? //每5秒執行壹次
public void execute(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now().toDate())+"*********B任務每5秒執行壹次進入測試"); ?
}?
}