Offer

SpringBoot-定时任务

springboot-定时任务

everthing will be okay....

实现结果如下:

UTOOLS1602489797623.png

  1. 添加依赖包
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
</dependencies>
  1. 添加相关注释

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
    	public static void main(String[] args) {
    		SpringApplication.run(Application.class, args);
    	}
    }
    
  2. 定时任务实现(CRON表达式与自定义时间)

    package com.empirefree.component;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    /**
     * @ProjectName: SchedulerTask
     * @Package: com.empirefree.component
     * @Description:
     * @Author: huyuqiao
     * @CreateDate: 2020/10/12 16:01
     */
    @Component
    public class SchedulerTask {
    
        private int count=0;
    
        @Scheduled(cron="*/6 * * * * ?")
        private void process(){
            System.out.println("this is scheduler task runing  "+(count++));
        }
    
    }
    
    package com.empirefree.component;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @ProjectName: Scheduler2Task
     * @Package: com.empirefree.component
     * @Description:
     * @Author: huyuqiao
     * @CreateDate: 2020/10/12 16:01
     */
    @Component
    public class Scheduler2Task {
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 6000)
        public void reportCurrentTime() {
            System.out.println("现在时间:" + dateFormat.format(new Date()));
        }
    
    }
    
posted @ 2020-10-12 16:25  Empirefree  阅读(98)  评论(0编辑  收藏  举报