Java专题十六:定时任务
2021-02-07 14:19
标签:lis sch 依赖 hat str htm read map rate 1.添加依赖包(gradle) 除了添加定时任务jar包,还需要添加slf4j 和 log4j整合用的日志文件,详情参考官网 2.新建工作类 3.设置并启动定时器开始执行工作 Java专题十六:定时任务 标签:lis sch 依赖 hat str htm read map rate 原文地址:https://www.cnblogs.com/myibu/p/12775701.htmlJava专题十六:定时任务
注意测试这些类时应该在主线程总执行,即main方法中执行,如果单元测试使用junit测试不出效果
16.1. java.lang.Thread类
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类
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类
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包
compile ‘org.quartz-scheduler:quartz:2.3.0‘
compile ‘org.slf4j:slf4j-log4j12:1.7.10‘
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");
}
}
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