微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

怎么通过spring做调度任务

本篇内容主要讲解“怎么通过spring做调度任务”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么通过spring做调度任务”吧!

构建工程
创建一个Springboot工程,在它的程序入口加上@EnableScheduling开启调度任务。

@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就打印出了当前的时间。
2017-04-29 17:39:37.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is Now 17:39:37
2017-04-29 17:39:42.671 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is Now 17:39:42
2017-04-29 17:39:47.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is Now 17:39:47
2017-04-29 17:39:52.675 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is Now 17:39:52

到此,相信大家对“怎么通过spring做调度任务”有了更深的了解,不妨来实际操作一番吧!这里是编程之家网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐