定时任务:我们在项目中,会使用定时任务去执行一些业务上或者是项目数据的备份和更新的操作,那么我们在微服务架构中怎么使用定时任务呢?又有多少种定时任务的实现方式呢?而定时任务的原理又是什么呢?
1. Timer 和 ScheduledExecutorService
Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。但是不能指定时间运行,所以使用在使用场景上较为局限!
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer {
public static void main(String args[]){
System.out.println("About to schedule task.");
new Reminder(3);
System.out.println("Task scheduled.");
}
public static class Reminder{
Timer timer;
public Reminder(int sec){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
System.out.println("Time's up!");
timer.cancel();
}
}, sec*1000);
}
}
}
ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用。
public class ScheduledExecutorServiceTest {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("run "+ System.currentTimeMillis());
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
}
2.Spring 配置定时任务
在Spring中,通过Spring的配置文件进行注入定时任务的配置类,注入定时任务的执行类,通过标签定义。
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=" http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd”
<description>
定时任务
</description>
//定时注解驱动
<task:annotation-driven />
//进行定时任务的类,将其定义为一个bean
<bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
//通过task标签,定义定时功能
<task:scheduled-tasks>
<task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" />
</task:scheduled-tasks>
代码实现
@Service
public class