java-定时任务调度工具Timer/Quartz|springboot整合定时调度

版权声明:fromZjy QQ1045152332 https://blog.csdn.net/qq_36762677/article/details/82761839

什么是定时任务调度

定时任务调度:基于给定的时间点,给定的时间间隔或者给定的执行次数自动执行任务。

两种java定时任务调度工具却别

Timer Quartz
小弟!功能简单,开销小 大哥!强大完善
jdk1.5 需要引入jar包
一个后台线程 后台执行线程池

Timer

简介:

有且仅有一个后台线程,对多个业务线程进行定时定频率的调度

主要构件:

Timer类中两个成员变量:

  1. TimerThread后台线程
  2. TaskQueue成员TimerTask[]

TimerThread的run方法来回调用TimerTask的run方法
总之,Timer–定时调用 TimerTask

实现

编写MyTimerTask类继承TimerTask类并重写run()方法,然后用Timer调用schedule方法来执行任务

import java.util.TimerTask;
public class MyTimerTask extends TimerTask{
	private String name;
	public MyTimerTask(String name){
		this,name = name;
	}
	@Override
	public void run(){
		System.out.println("This thread is " + this,name);
	}
	//set get
}

Timer类

public class MyTimer{
	public static void main(String[] args){
		Timer timer = new Timer();
		MyTimerTask myTimerTask = new MyTimerTask ("name1");
		//通过timer定时调用myTimerTask的run
		//2秒之后执行,此后每3秒执行一次
		timer.schedule(myTimerTask,2000L,3000L);
	}
}

当然,还有其他schedule其他用法
1.timer.schedule(task,time);//time距1970年的毫秒数,只执行一次
2.timer.schedule(task,time,period);//time首次执行任务时间,每隔period毫秒再执行
3.timer.schedule(task,delay);//等待delay毫秒后,执行且仅执行一次task
4.timer.schedule(task,delay,period);/等待delay毫秒后,每隔period毫秒再执行
scheduleAtFixedRate的两种用法(暂时理解为同上)
1.timer.scheduleAtFixedRate(task,time,period);//和上面第二种方法一样
2.timer.scheduleAtFixedRate(task,delay,period);//和上面第四种方法一样

其他重要函数

TimerTask的两个函数

  • cancel() 取消当前TimerTask里的任务[在类里执行]
  • scheduledExecutionTime(),返回最近发生此任务的时间 毫秒[在主方法里执行myTimerTask.scheduledExecutionTime()]
import java.util.TimerTask;
public class MyTimerTask extends TimerTask{
	private String name;
	private int count = 0;
	public MyTimerTask(String name){
		this,name = name;
	}
	@Override
	public void run(){
		System.out.println("This thread is " + this,name);
		count++;
		if(count==3){
			//□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□
			cancel();//取消当前任务运行!!!!!!!!!!!!!!!!
			//□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□
		}
	}
	//set get
}

Timer的两个函数

  • cancel() 中止所有安排的任务
  • purge() 移除队列中已取消的任务,返回溢出的任务数

springboot整合定时任务task

使用@EnableScheduling注解开启定时任务,会自动扫描到
定义组件被容器扫描@Component

//主要启动类
@SpringBootApplication()
@EnableScheduling
@MapperScan("com.***.dao")
public class managerToolApplication {
	public static void main(String[] args) {
		ProcessUtil.setProcessID();
		ApplicationContext app = SpringApplication.run(managerToolApplication.class, args);
		SpringUtil.setApplicationContext(app);
		SpringUtil.scannerBeans();
	}
}
//定时计划类
@Component
public class AlarmTask {
	/**
	** @Scheduled(fixedRate = 2000)第一种:每两秒执行一次
	 * @Scheduled(cron = "0 0/10 * * * ?")第二种 :cron表达式
	*/
	@Scheduled(cron = "0 0/1 * * * ?")
    public void computerMonitor() {
		//具体逻辑
	}
}

六位 0 0/10 * * * ?
springboot不支持年
在线自动生成cron
秒 分 时 日 月 年
4-40 4到40秒打印
0/10 从0开始,每10秒一执行

猜你喜欢

转载自blog.csdn.net/qq_36762677/article/details/82761839