zoukankan      html  css  js  c++  java
  • SpringBoot配置定时任务的两种方式

    一、导入相关的jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

    二、启动类启用定时

    在启动类上面加上 @EnableScheduling 即可开启定时

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

    三、创建定时任务实现类

    第1种实现方式:

    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    public class Scheduler1Task {
        private int count = 0;
    
        @Scheduled(cron = "*/6 * * * * ?")/*每隔六秒钟执行一次*/
        private void process() {
            System.out.println("this is scheduler task runing  " + (count++));
        }
    }

    第2种实现方式:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Component
    public class Scheduler2Task {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Autowired
        private JavaMailSender mailSender;
    
        /*
         * @Scheduled(fixedRate = 6000) 上一次开始执行时间点之后6秒再执行
         * @Scheduled(fixedDelay = 6000) 上一次执行完毕时间之后6秒再执行
         * @Scheduled(initialDelay=1000, fixedRate=6000) 第一次延迟1秒后执行,之后按fixedRate的规则执行
         * */
        @Scheduled(fixedRate = 6000)/*每隔六秒钟执行一次*/
        public void reportCurrentTime() {
            System.out.println("现在时间:" + dateFormat.format(new Date()));
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("542813934@qq.com");
            message.setTo("542813934@qq.com");
            message.setSubject("主题:简单邮件1");
            message.setText("测试邮件内容1");
            mailSender.send(message);
        }
    }
  • 相关阅读:
    [转]SDRAM中的一些疑惑点
    [转]如何学习小波分析?
    [转]功率谱和频谱的区别、联系
    使用Vim为每一行自动编号
    [转]阿英 Matlab fftshift 详解
    [转]性噪比和相位失真
    神舟笔记本精盾K480N高频噪声消除方法
    Tips:verilog计数分频计算
    vim的列编辑操作
    【题解】 「CTSC2018」暴力写挂 点分治+虚树+树形dp LOJ2553
  • 原文地址:https://www.cnblogs.com/zhanzhuang/p/10244159.html
Copyright © 2011-2022 走看看