java后台实现定时任务

2019年7月19日 基于注解@Scheduled默认为单线程,任务的执行时机会受上一个任务执行时间的影响。

fixedRate配置了上一次任务的开始时间下一次任务的开始时间的间隔,每次任务都会执行;
fixedDelay配置了上一次任务的结束时间下一次任务的开始时间的间隔,每次任务都会执行;
cron表达式配置了在哪一刻执行任务,会在配置的任务开始时间判断任务是否可以执行,如果能则执行,不能则会跳过本次执行;
如果是强调任务间隔的定时任务,建议使用fixedRate和fixedDelay,如果是强调任务在某时某分某刻执行的定时任务,建议使用cron表达式。

这里使用fixedDelay的原因是:它的间隔时间是根据上次的任务结束的时候开始计时的,比如我这里设置的15分钟间隔,也就是意味着下次执行任务的时间开始计算是上次执行任务结束的时间,当时间间隔为15分钟时,再次开始执行该任务。

而fixedRate它的计算时间是根据上次任务开始的时间计时的,比如fixedRate设置的间隔时间为5秒,如果执行此任务所耗费的时间为3秒,那2任务结束后的两秒任务就会再次执行,但如果任务执行的时间超过了5秒,就会出现阻塞,具体有什么影响,目前我还没有测试,如果好奇的小伙伴可以自己动手试下

import io.renren.modules.generator.service.OfficialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    @Autowired
    private OfficialService officialService;
    //基于注解@Scheduled默认为单线程
    //3.添加定时任务
    //或直接指定时间间隔,例如:1秒(1000), 1分钟(60000)
    @Scheduled(fixedDelay=15*60*1000 )
    private void configureTasks() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd hh:mm:ss");
        String data=sdf.format(new Date());
        System.err.println("获取并更新公众号用户列表定时任务,执行时间: " + data);
        System.err.println("数据获取开始时间: " + sdf.format(new Date()));
        officialService.getWXopenids(); //调用方法
        System.err.println("数据获取结束时间: " + sdf.format(new Date()));

    }
}
<!--定时任务添加依赖-->
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>5.1.0.RELEASE</version>
</dependency>
发布了46 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33238562/article/details/96480290