Spring Scheduled 定時任務 + 異步執行


Spring定時任務 + 異步執行

1.實現spring定時任務的執行

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

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

@Component
public class ScheduledTasks {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");

    @Scheduled(fixedDelay = 5000)
    public void first() throws InterruptedException {
        System.out.println("第一個定時任務開始 : " + sdf.format(new Date()) + "\r\n線程 : " + Thread.currentThread().getName());
        System.out.println();
        Thread.sleep(1000 * 10); //模擬第一個任務執行的時間
    }

    @Scheduled(fixedDelay =3000)
    public void second() {
        System.out.println("第二個定時任務開始 : " + sdf.format(new Date()) + "\r\n線程 : " + Thread.currentThread().getName());
        System.out.println();
    }
}

由於執行定時任務默認的是單線程,存在的問題是:

​ 線程資源被第一個定時任務占用,第二個定時任務並不是3秒執行一次;

解決方法,創建定時任務的線程調度器,交給spring管理調度

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class ScheduleConfig {

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }
}

這樣就可以保證定時任務之間是多線程,而每個定時任務之間是單線程,保證了定時任務的異步,同時保證了消息的冪等性


免責聲明!

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



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