springboot下使用@Scheduled和@Async

有一點很重要(這是我放在最前面的原因):調用被@Async註解的方法時,調用方法不能與被調用方法放在同一類中,否則註解不生效
因此,我們應該這樣做:
一個類中實現被調用方法,另一個類進行調用
在這裏插入圖片描述
在這裏插入圖片描述
在啓動類上加@EnableAsync和@EnableScheduling

import com.spring4all.mongodb.EnableMongoPlus;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableAsync
@EnableScheduling
@EnableTransactionManagement(proxyTargetClass = true)
@EnableMongoPlus
@SpringBootApplication
public class MpfcontrolApplication {

    public static void main(String[] args) {
        // SpringApplication.run(MpfcontrolApplication.class, args);
        new SpringApplicationBuilder(MpfcontrolApplication.class).headless(false).run(args);

        ViewStart.run();
    }

}

使用 @Scheduled(fixedRate=10000)實現定時間間隔調用(單位毫秒)

 //定時調用批處理方法
    @Scheduled(fixedRate=10000)
    public void doTimer(){
//        System.out.println("定時執行");
        JSONObject json=new JSONObject();
        batchAddSystemLog(json,2);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章