java--定时器

《一》非注解-定时器

package com.example.demo;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author cuitao
 * @ className:
 * @ description:
 * @ create 2021-01-06 21:23
 **/
public class RunnableForTimer {


    public static void main(String[] args) {
        /**
         * Runnable:实现了Runnable接口,jdk就知道这个类是一个线程
         */
        Runnable runnable = new Runnable() {
            //创建 run 方法
            @Override
            public void run() {
                // task to run goes here
                System.out.println("需要定时处理的业务");
            }
        };
        // ScheduledExecutorService:是从Java SE5的java.util.concurrent里,
        // 做为并发工具类被引进的,这是最理想的定时任务实现方式。
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
        // 10:秒   5:秒
        // 第一次执行的时间为10秒,然后每隔五秒执行一次
        service.scheduleAtFixedRate(runnable, 10, 5, TimeUnit.SECONDS);
    }

}

《二》注解的方式实现springboot的定时任务

  • 方法一:
  • 直接在定时器类上添加@Configuration、@EnableScheduling注解,标注这个类是配置文件,并开启定时开关;
  • 给要定时执行方法上添加@Scheduled(cron = "0 0 0 * * * ")
  • 这样当程序启动后,就会按配置的规则定时跑程序
  • package com.example.demo;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    
    /**
     * @author cuitao
     * @ className:
     * @ description:
     * @ create 2021-01-06 22:04
     **/
    @Configuration          //证明这个类是一个配置文件
    @EnableScheduling       //启用定时器
    public class ScheduleTimer {
        @Scheduled(cron = "0/2 * * * * *")
        public void runTimer(){
            System.out.println("要定时跑的程序");
    
        }
    }
    
  • 方法二:
  • 在启动类上添加注解@EnableScheduling开启定时器总开关
  • @SpringBootApplication
    @EnableScheduling
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }

    给要定时执行的方法上添加注解@Scheduled(cron = "0 0 0 * * * ")
    这样当程序启动后,就会按配置的规则定时跑程序

    package com.example.demo;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    /**
     * @author cuitao
     * @ className:
     * @ description:
     * @ create 2021-01-06 22:04
     **/
    @Component
    public class ScheduleTimer {
        @Scheduled(cron = "0/2 * * * * *")
        public void runTimer(){
            System.out.println("要定时跑的程序");
    
        }
    }
    

    《三》XXL-JOB

  •  

猜你喜欢

转载自blog.csdn.net/CUITAO2305532402/article/details/112298902