企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## Java专题十六:定时任务 [TOC] 注意测试这些类时应该在主线程总执行,即main方法中执行,如果单元测试使用junit测试不出效果 ### 16.1. java.lang.Thread类 ```java public class ThreadTest { public static void main(String[] args){ Runnable beeper = new Runnable() { public void run() { while (true){ System.out.println("beep"); try { /* 执行周期为3s */ Thread.sleep(3 * 1000); }catch(InterruptedException e){ e.printStackTrace(); } } } }; Thread thread = new Thread(beeper); thread.start(); } } ``` ### 16.2. java.util.Timer类 ```java import java.util.Timer; import java.util.TimerTask; public class TimerTest{ public static void main(String[] args){ Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { System.out.println("beep"); } }; /* 2s后开始执行,执行周期为3s */ timer.scheduleAtFixedRate(timerTask, 2 *1000, 3 * 1000); } } ``` ### 16.3. java.util.concurrent.ScheduledExecutorService类 ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorServiceTest{ public static void main(String[] args){ ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; /* 2s后开始执行,执行周期为3s */ scheduler.scheduleAtFixedRate(beeper, 2, 3, TimeUnit.SECONDS); } } ``` ### 16.4. 第三方quartz包 1.添加依赖包(gradle) ``` compile 'org.quartz-scheduler:quartz:2.3.0' compile 'org.slf4j:slf4j-log4j12:1.7.10' ``` 除了添加定时任务jar包,还需要添加slf4j 和 log4j整合用的日志文件,详情参考[官网](http://www.quartz-scheduler.org/documentation/quartz-2.2.x/quick-start.html#quartz-quick-start-guide) 2.新建工作类 ```java import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class BeepJob implements Job { public BeepJob(){ } @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap dataMap = context.getJobDetail().getJobDataMap(); System.out.println(dataMap.get("msg")); System.err.println("BeepJob Executed"); } } ``` 3.设置并启动定时器开始执行工作 ```java import org.quartz.*; import org.quartz.impl.StdSchedulerFactory ;import java.util.Date; import java.util.HashMap; import java.util.Map; public class ScheduleTest { public static void main(String[] args){ SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = null; try { scheduler = sf.getScheduler(); /* 使用JobDetail中的JobDataMap携带数据 */ Map<String, Object> dataMap = new HashMap<>(); dataMap.put("msg", "beep"); JobDataMap jobDataMap = new JobDataMap(dataMap); /* 定义JobDetail */ JobDetail job = JobBuilder.newJob(BeepJob.class) .withIdentity("beep-job", "beep") .usingJobData(jobDataMap) .build(); /* 定义开始时间 */ Date date = new Date(System.currentTimeMillis() + 2 * 1000); /* Define a Trigger that will fire "date", and repeat forever, 2s后开始执行,执行周期为3s */ Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("beep-trigger", "beep") .startAt(date) .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(3) .repeatForever()) .build(); /* Tell quartz to schedule the job using our trigger */ scheduler.scheduleJob(job, trigger); scheduler.start(); }catch (SchedulerException e){ e.printStackTrace(); } } } ```