Springboot之配置定時任務


1、在啟動類上加注解開啟定時任務(定時任務可以寫在啟動類中)

package com.gxr.imybatisplus;

import com.gxr.imybatisplus.service.schedule.MyScheduleService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@MapperScan("com.gxr.imybatisplus.mapper")
@EnableScheduling
public class IMybatisPlusApplication {

    @Autowired
    MyScheduleService Myservice;

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

    /**
     * 定時執行,每次插入一條數據
     */
    @Scheduled(cron = "*/5 * * * * ?")
    private void ScheduleTask() {
        String tableName = "t_sample_s_pg1";
        Myservice.insertOne(tableName);
    }

}

 

 

2、編寫測試定時任務類 

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

@Service
public class MySchedule {
    private final Logger logger = Logger.getLogger(this.getClass().getName());


    /**
     * 定時任務舉例
     */
    @Scheduled(cron = "0/1 * * * * *")
    public void test() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date()));
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM