ITPub博客

首页 > 架构设计 > > SpringCloud分布式微服务b2b2c电子商务-定时任务

SpringCloud分布式微服务b2b2c电子商务-定时任务

作者:gung123 时间:2020-01-10 14:58:21 0 删除 编辑

这篇文章将介绍怎么通过spring去做调度任务。

构建工程
创建一个Springboot工程,在它的程序入口加上@EnableScheduling,了解springcloud架构可以加求求:三五三六二四七二五九,开启调度任务。

@SpringBootApplication
@EnableScheduling
public class SpringbootSchedulingTasksApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootSchedulingTasksApplication.class, args);
}
}

创建定时任务
创建一个定时任务,每过5s在控制台打印当前时间。 

@Component
public class ScheduledTasks {

private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
通过在方法上加@Scheduled注解,表明该方法是一个调度任务。

@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron=” /5 “) :通过cron表达式定义规则,什么是cro表达式,自行搜索引擎。
测试
启动springboot工程,控制台没过5s就打印出了当前的时间。


 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69952307/viewspace-3134404/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-11-01

  • 博文量
    200
  • 访问量
    79619