springboot基礎學習5 定時任務

2021-09-29 08:02:18 字數 3137 閱讀 4402

一、在我們開發中經常會使用到定時任務來處理一些業務,而我們會使用不同的框架來實現任務的排程。

這裡使用spring中封裝的任務排程來與springboot進行整合

1、首先新增依賴 場景啟動器 starter,這裡使用的是2.1.4.release版本

pom.xml檔案中新增依賴

org.springframework.boot<

/groupid>

spring-boot-starter<

/artifactid>

<

/dependency>

org.springframework.boot<

/groupid>

spring-boot-starter-test<

/artifactid>

test<

/scope>

<

/dependency>

2、編寫兩個類

乙個 asyncservice類

package org.learn.boot.task.service;

import org.springframework.scheduling.annotation.async;

import org.springframework.stereotype.service;

/** * 非同步service

* @classname: asyncservice

* @description:

* @author: lin

* @date: 2019/9/27 20:35

* history:

* @1.0

*/@service

public

class

asyncservice

catch

(interruptedexception e)

long end = system.

currenttimemillis()

; system.out.

println

("處理資料中......"

+ end);}

}

乙個 scheduleservice類

package org.learn.boot.task.service;

import org.springframework.scheduling.annotation.scheduled;

import org.springframework.stereotype.service;

/** * 任務排程 service

* @classname: scheduleservice

* @description:

* @author: lin

* @date: 2019/9/27 20:47

* history:

* @1.0

*/@service

public

class

scheduleservice

means once per minute on weekdays

* 這個註解 加了之後還要在啟動類中開啟 任務排程的註解 @enablescheduling

* 下面是每2s執行一次

* 注意這個的星期 1-6 表示周一到週六,但是0和7表示都能代表週日, 這個與quartz 框架 不同 quartz 中 1-7中 1代表週日,2代表周一

* 而這個spring的排程 框架 是0和7表示都能代表週日。 這點要特別注意

** 秒 分 時 日 月 周

* [0 0/5 14,18 * * ? ] 每天14點整, 和18點整,每隔5分鐘執行一次

* [0 15 10 ? * 1-6] 每個月的周一到周五10:15分執行一次

* [0 0 2 ? * 6l] 每個月的最後乙個週六凌晨2點執行一次

* [0 0 2 lw * ?] 每個月的最後乙個工作日凌晨2點執行一次 ,lw 是最後乙個工作日

* [0 0 2-4 ? * 1#1] 每個月的第乙個周一凌晨2點到4點期間,每個整點都執行一次**/

@scheduled

(cron =

"*/2 * * * * *"

)public

void

schedule()

}

3、寫乙個controller類

*

/@restcontroller

public

class

asynccontroller

}

4、我們需要在啟動類中去開啟任務排程,並且開啟非同步執行

package org.learn.boot.task;

import org.springframework.scheduling.annotation.enableasync;

import org.springframework.scheduling.annotation.enablescheduling;

/** * @author lin

* @enableasync 開啟非同步任務

* @enablescheduling 基於註解的定時任務

*/@enablescheduling

@enableasync

public

class

}

5、啟動進行測試,從測試結果來看是每隔2s列印一次。

6、我們在來測非同步執任務

請求 介面位址http://localhost:8090/hello

多次請求結果如下,會去非同步的執行。而如果這個方法上沒有 @async註解那麼就會等待上一次請求執行完了才執行

參考:

彙編基礎學習5

文章 http www.mcany.cn article 280.htm 博主 沒落的殘陽 今天我給大家來講解下我們記憶體中資料的儲存以及訪問。這節課的基礎也是非常重要的。因為80386的資料位址線是32根,所以它一次可以傳送資料是4個位元組。所以我們記憶體單元是按照4個位元組來對齊的。用高階語言的...

php 基礎學習5

主要包括php的錯誤 異常處理和除錯。具體如下 1 256 8 php的錯誤 異常處理和除錯9 1011 12 常見的錯誤型別 13 語法錯誤 14 邏輯錯誤 15 未定義錯誤 16 環境錯誤 17 執行錯誤 18 1920 21 錯誤處理函式 22 在php中,可以使用trigger error ...

python基礎學習 5

第一種建立方式,直接使用小括號t 10,20,30,40,hello print t 10,20,30,40,hello 第二種建立方式,使用tuple 內建函式 t1 tuple 10,20,30,40,hello print t1 10,20,30,40,hello s print s 第二種建...