1. Java实现定时任务方式
public class Demo01 {
staticlongcount = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
publicvoid run() {
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println(count);
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
2. TimerTask实现定时任务
/**
* 使用TimerTask类实现定时任务
*/
public class Demo02 {
static long count = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
publicvoid run() {
count++;
System.out.println(count);
}
};
Timer timer = new Timer();
// 天数
longdelay = 0;
// 秒数
longperiod = 1000;
timer.scheduleAtFixedRate(timerTask, delay, period);
}
}
3.ScheduledExecutorService 实现
publicclass Demo003 {
publicstaticvoid main(String[] args) {
Runnable runnable = new Runnable() {
publicvoid run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorServiceservice = Executors.newSingleThreadScheduledExecutor();
// 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
}
}
4.spring boot+ quartz 实现方式
1.引入maven依赖
<!-- quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
2.任务调度类
publicclass MyJob implements Job {
publicvoid execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("quartz MyJob date:" + new Date().getTime());
}
}
3.启动任务类
//1.创建Scheduler的工厂
SchedulerFactory sf = new StdSchedulerFactory();
//2.从工厂中获取调度器实例
Scheduler scheduler = sf.getScheduler();
//3.创建JobDetail
JobDetail jb = JobBuilder.newJob(MyJob.class)
.withDescription("this is a ram job") //job的描述
.withIdentity("ramJob", "ramGroup") //job 的name和group
.build();
//任务运行的时间,SimpleSchedle类型触发器有效
longtime= System.currentTimeMillis() + 3*1000L; //3秒后启动任务
Date statTime = new Date(time);
//4.创建Trigger
//使用SimpleScheduleBuilder或者CronScheduleBuilder
Trigger t = TriggerBuilder.newTrigger()
.withDescription("")
.withIdentity("ramTrigger", "ramTriggerGroup")
//.withSchedule(SimpleScheduleBuilder.simpleSchedule())
.startAt(statTime) //默认当前时间启动
.withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
.build();
//5.注册任务和定时器
scheduler.scheduleJob(jb, t);
//6.启动调度器
scheduler.start();
来源:CSDN
作者:houxian1103
链接:https://blog.csdn.net/houxian1103/article/details/104107826