springBoot(9)---定時任務,異步任務


定時任務,異步任務

 

一、定時任務

 

1、步驟:

         1:在啟動類上寫@EnableScheduling注解

         2:在要定時任務的類上寫@component 

         3:在要定時執行的方法上寫@Scheduled(fixedRate=毫秒數)。

 

2、示例

    主類

@SpringBootApplication
@EnableScheduling //開啟定時任務
public class MainApplication {

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

     定時任務類

import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component public class Jobs {
  
    //表示方法執行完成后5秒
    @Scheduled(fixedDelay=5000)
    public void fixedDelayJob() throws InterruptedException{  
        System.out.println("fixedDelay 每隔5秒"+new Date());
    }
    
    //表示每隔3秒
    @Scheduled(fixedRate=3000)
    public void fixedRateJob(){
        
        System.out.println("fixedRate 每隔3秒"+new Date());
    }

    //表示每天8時30分0秒執行
    @Scheduled(cron="0 0,30 0,8 ? * ? ")
public void cronJob(){ System.out.println(new Date()+" ...>>cron...."); } }

效果:

 

 3.總結

  1.fixedDelayfixedRate,單位是毫秒,這里這里就是5秒和3秒,它們的區別就是

fixedRate就是每多次分鍾一次,不論你業務執行花費了多少時間。我都是1分鍾執行1次,而fixedDelay是當任務執行完畢后1分鍾在執行。所以根據實際業務不同,我們會選擇不同的方式。

  2.cron表達式:比如你要設置每天什么時候執行,就可以用它

     cron表達式,有專門的語法,而且感覺有點繞人,不過簡單來說,大家記住一些常用的用法即可,特殊的語法可以單獨去查。
     cron一共有7位,但是最后一位是年,可以留空,所以我們可以寫6位:

* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小時,取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
          另外:1表示星期天,2表示星期一。
* 第7為,年份,可以留空,取值1970-2099

     cron中,還有一些特殊的符號,含義如下:

(*)星號:可以理解為每的意思,每秒,每分,每天,每月,每年...
(?)問號:問號只能出現在日期和星期這兩個位置。
(-)減號:表達一個范圍,如在小時字段中使用“10-12”,則表示從10到12點,即10,11,12
(,)逗號:表達一個列表值,如在星期字段中使用“1,2,4”,則表示星期一,星期二,星期四
(/)斜杠:如:x/y,x是開始值,y是步長,比如在第一位(秒) 0/15就是,從0秒開始,每15秒,最后就是0,15,30,45,60    另:*/y,等同於0/y

      下面列舉幾個例子供大家來驗證:

0 0 3 * * ?     每天3點執行
0 5 3 * * ?     每天3點5分執行
0 5 3 ? * * 每天3點5分執行,與上面作用相同
0 5/10 3 * * ?  每天3點的 5分,15分,25分,35分,45分,55分這幾個時間點執行
0 10 3 ? * 1 每周星期天,3點10分 執行,注:1表示星期天    
0 10 3 ? * 1#3  每個月的第三個星期,星期天 執行,#號只能出現在星期的位置

 

二、異步任務

   1、步驟

             1: 啟動類里面使用@EnableAsync注解開啟功能,自動掃描

             2:在要異步任務的類上寫@component 

             3:在定義異步任務類寫@Async(寫在類上代表整個類都是異步,在方法加上代表該類異步執行)

 

  2、示例

   主類

@SpringBootApplication
@EnableAsync //開啟異步任務
public class MainApplication {

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

  異步類

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * 功能描述:異步任務業務類
 */ @Component
@Async public class AsyncTask {
    

    //獲取異步結果
    public Future<String> task4() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任務4耗時="+(end-begin));
        return new AsyncResult<String>("任務4");
    }
    
    
    public Future<String> task5() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任務5耗時="+(end-begin));
        return new AsyncResult<String>("任務5");
    }
    
    public Future<String> task6() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任務6耗時="+(end-begin));
        return new AsyncResult<String>("任務6");
    }
        
}

  controller類

import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jincou.task.AsyncTask;
import com.jincou.util.JsonData;

@RestController
@RequestMapping("/api/v1")
public class UserController {
    
    @Autowired
    private AsyncTask task;
    
    @GetMapping("async_task")
    public JsonData exeTask() throws InterruptedException{
        
        long begin = System.currentTimeMillis();
        
        Future<String> task4 = task.task4();
        Future<String> task5 = task.task5();
        Future<String> task6 = task.task6();
        
        //如果都執行往就可以跳出循環,isDone方法如果此任務完成,true
        for(;;){
            if (task4.isDone() && task5.isDone() && task6.isDone()) {
                break;
            }
        }
                
        long end = System.currentTimeMillis();    
        long total = end-begin;
        System.out.println("執行總耗時="+total);
        return JsonData.buildSuccess(total);
    }    
}

結果:

頁面:

后台:

 

 3、總結

 從上面示例我們可以看出:如果同步方法,那我們需要6秒,而異步執行,我們只需要3秒左右,這就是異步的作用。

     1)要把異步任務封裝到類里面,不能直接寫到Controller
     2)增加Future<String> 返回結果 AsyncResult<String>("task執行完成");
     3)如果需要拿到結果 需要判斷全部的 task.isDone()

 

 想太多,做太少,中間的落差就是煩惱。想沒有煩惱,要么別想,要么多做。上尉【10】

 

 

 

 

 

 

    


免責聲明!

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



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