国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

2020-07-28 00:07實(shí)習(xí)小生 Java教程

這篇文章主要介紹了springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的相關(guān)知識,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

這篇文章給大家介紹springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù),詳情如下所示:

篇幅較長,耐心的人總能得到最后的答案小生第一次用quartz做定時任務(wù),不足之處多多諒解。

首先

在springboot項(xiàng)目里做定時任務(wù)是比較簡單的,最簡單的實(shí)現(xiàn)方式是使用**@Scheduled注解,然后在application啟動類上使用@EnableScheduling**開啟定時任務(wù)。

示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@SpringBootApplication
@EnableScheduling
public class Application {
 
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
 // cron為每秒執(zhí)行一次
 @Scheduled(cron = "* * * * * ?")
 public void print(){
 System.out.println("執(zhí)行定時任務(wù)");
 }
 
}

######結(jié)果

執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)
執(zhí)行定時任務(wù)

簡單的定時任務(wù)就可以用這種方式來做,cron表達(dá)式的結(jié)果為任務(wù)執(zhí)行的間隔時間。

然而

實(shí)際開發(fā)中,我們的任務(wù)可能有很多,且需要手動操作單個/全部的任務(wù),比如添加、開啟、停止、繼續(xù)等等操作。那么伴隨著(千牛B類。。。)的BGM有請quartz登場。

quartz

整合

?
1
2
3
4
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

quartz的三要素

  • 調(diào)度器Scheduler
  • 啟動觸發(fā)器去執(zhí)行任務(wù)
  • 觸發(fā)器Trigger

用來定義Job(任務(wù))觸發(fā)條件、觸發(fā)時間,觸發(fā)間隔,終止時間等

任務(wù)job

具體要執(zhí)行的任務(wù)內(nèi)容

使用

使用quartz是需要配置文件的,quartz.properties在quartz的jar包的org.quartz包下可以找到默認(rèn)的配置文件quartz.properties

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
# 名字
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
# 實(shí)例化ThreadPool時,使用的線程類為SimpleThreadPool
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
# 線程總個數(shù)
org.quartz.threadPool.threadCount: 10
# 線程的優(yōu)先級
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
 
org.quartz.jobStore.misfireThreshold: 60000
# 持久化方式,默認(rèn)持久化在內(nèi)存中,后面我們使用db的方式
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

quartz任務(wù)持久化到db則需要一些官方定義的數(shù)據(jù)庫表,表的sql文件可以在quartz的jar包里找到

坐標(biāo)org.quartz.impl.jdbcjobstore,可以看到里面有很多sql文件,有各種數(shù)據(jù)庫的,咱們用MySQL的,咱們不需要手動執(zhí)行sql語句,后面咱們在啟動項(xiàng)目的時候自動初始化。

創(chuàng)建我們自己的properties文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 實(shí)例化ThreadPool時,使用的線程類為SimpleThreadPool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
# threadCount和threadPriority將以setter的形式注入ThreadPool實(shí)例
# 并發(fā)個數(shù)
org.quartz.threadPool.threadCount=10
# 優(yōu)先級
org.quartz.threadPool.threadPriority=5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
org.quartz.jobStore.misfireThreshold=5000
#持久化使用的類
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
#數(shù)據(jù)庫中表的前綴
org.quartz.jobStore.tablePrefix=QRTZ_
#數(shù)據(jù)源命名
org.quartz.jobStore.dataSource=qzDS
#qzDS 數(shù)據(jù)源,我們使用hikaricp,默認(rèn)的是c3p0
org.quartz.dataSource.qzDS.provider=hikaricp
org.quartz.dataSource.qzDS.driver=com.mysql.cj.jdbc.Driver
org.quartz.dataSource.qzDS.URL=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
org.quartz.dataSource.qzDS.user=root
org.quartz.dataSource.qzDS.password=123456
org.quartz.dataSource.qzDS.maxConnections=10

既然我們沒有使用默認(rèn)的連接池,那么就探索一下,上源碼!在這個包下:org.quartz.utils,有一個PoolingConnectionProvider,顧名思義,連接池提供者部分源碼

?
1
2
3
4
5
6
7
8
9
10
11
12
public interface PoolingConnectionProvider extends ConnectionProvider {
 
 /** The pooling provider. */
 String POOLING_PROVIDER = "provider";
 
 /** The c3p0 pooling provider. */
 String POOLING_PROVIDER_C3P0 = "c3p0";
 
 /** The Hikari pooling provider. */
 String POOLING_PROVIDER_HIKARICP = "hikaricp";
 
}

然后HikariCpPoolingConnectionProvider這個類實(shí)現(xiàn)了PoolingConnectionProvider,自行查看。我們可以在org.quartz.impl下的StdSchedulerFactory中搜索c3p0找到

?
1
2
3
4
5
6
if(poolingProvider != null && poolingProvider.equals(PoolingConnectionProvider.POOLING_PROVIDER_HIKARICP)) {
   cpClass = "org.quartz.utils.HikariCpPoolingConnectionProvider";
   }
   else {
   cpClass = "org.quartz.utils.C3p0PoolingConnectionProvider";
   }

剩下的自己多看看吧,起始源碼研究起來沒有想象中那么難那么乏味(我也不喜歡看源碼),但是這個源碼看起來確實(shí)小有成就感。

回到正題頻道,配置application.yml

?
1
2
3
4
5
6
7
8
9
10
spring:
 datasource:
 driver-class-name: com.mysql.cj.jdbc.Driver
 password: 123456
 url: jdbc:mysql://localhost:3306/quartz?characterEncoding=UTF8&useSSL=false&serverTimezone=GMT%2B8
 username: root
 quartz:
 jdbc:
 initialize-schema: always
 job-store-type: jdbc

initialize-schema: always每次啟動項(xiàng)目,總是初始化數(shù)據(jù)庫表自動創(chuàng)建表的關(guān)鍵地方,流程是先刪除數(shù)據(jù)庫表,再創(chuàng)建,如果表不存在,則拋異常,但是不會影響后面的生成表,下次再啟動項(xiàng)目的時候,由于表已經(jīng)存在了,所以不會再拋異常了job-store-type: jdbc就是任務(wù)持久化類型,我們用jdbc

我們可能要在job里注入spring對象,不做配置,是無法注入的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * @author: taoym
 * @date: 2020/6/4 11:32
 * @desc: 一定要自定義JobFactory重寫SpringBeanJobFactory的createJobInstance方法,否則在job中是獲取不到spring容器中的bean的
 */
@Component
public class JobFactory extends SpringBeanJobFactory {
 
 @Autowired
 private AutowireCapableBeanFactory beanFactory;
 
 /**
 * 這里覆蓋了super的createJobInstance方法,對其創(chuàng)建出來的類再進(jìn)行autowire
 */
 @Override
 protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
 Object jobInstance = super.createJobInstance(bundle);
 beanFactory.autowireBean(jobInstance);
 return jobInstance;
 }
}

創(chuàng)建quartz的配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@Configuration
public class QuartzConfig {
 
 @Autowired
 private JobFactory jobFactory;
 
 /**
 * 讀取quartz.properties 文件
 * 將值初始化
 *
 * @return
 */
 @Bean
 public Properties quartzProperties() throws IOException {
 PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
 propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
 propertiesFactoryBean.afterPropertiesSet();
 return propertiesFactoryBean.getObject();
 }
 
 @Bean
 public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
 SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
 schedulerFactoryBean.setJobFactory(jobFactory);
 schedulerFactoryBean.setQuartzProperties(quartzProperties());
 return schedulerFactoryBean;
 }
 
 /**
 * 初始化監(jiān)聽器
 *
 * @return
 */
 @Bean
 public QuartzInitializerListener executorListener() {
 return new QuartzInitializerListener();
 }
 
 
 @Bean(name = "scheduler")
 public Scheduler scheduler() throws IOException {
 return schedulerFactoryBean().getScheduler();
 }
}

創(chuàng)建觸發(fā)器組件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TriggerComponent {
 
 /**
 * @author: taoym
 * @date: 2020/6/1 10:35
 * @desc: 構(gòu)建cron觸發(fā)器
 */
 public static Trigger cronTrigger(String cron) {
 CronTrigger cronTrigger = TriggerBuilder.newTrigger()
  .withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing())
  .build();
 return cronTrigger;
 }
 
 public static Trigger cronTrigger(String cron, JobDataMap jobDataMap) {
 CronTrigger cronTrigger = TriggerBuilder.newTrigger()
  .withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing())
  .usingJobData(jobDataMap)
  .build();
 return cronTrigger;
 }
}

觸發(fā)器就用這個組件來獲取就行了。

創(chuàng)建任務(wù)

?
1
2
3
4
5
6
7
@DisallowConcurrentExecution
public class TestJob extends QuartzJobBean {
 @Override
 protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
 
 }
}

jobExecutionContext這里面可以獲取任務(wù)組、任務(wù)名、觸發(fā)器組、觸發(fā)器名、jobdetail等信息。那個注解是為了讓同一個實(shí)例(jobdetail)只能單線程執(zhí)行。可以這么理解,job為接口,jobdetail為實(shí)現(xiàn)類,a是其中一個實(shí)現(xiàn)類,a需要花費(fèi)100s執(zhí)行一定的操作,而你給的定時器是沒50s就執(zhí)行一次操作,a在執(zhí)行到一半的時候又需要開啟一個線程來執(zhí)行。使用了DisallowConcurrentExecution就相當(dāng)于a沒有把操作執(zhí)行完的時候,a不允許開啟線程再執(zhí)行當(dāng)前操作。不知道我的描述是否易懂!

按需創(chuàng)建自己的任務(wù)表,我是用定時任務(wù)做爬蟲的(小爬蟲)

?
1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE `quartz_job` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號',
 `job_name` varchar(50) DEFAULT '' COMMENT '任務(wù)名',
 `job_group` varchar(50) DEFAULT '' COMMENT '任務(wù)組名稱',
 `job_desc` varchar(255) DEFAULT '' COMMENT 'job描述',
 `cron` varchar(50) DEFAULT '' COMMENT 'cron表達(dá)式',
 `status` tinyint(1) DEFAULT '0' COMMENT '狀態(tài)',
 `url` varchar(255) DEFAULT '' COMMENT '請求地址',
 `param` varchar(255) DEFAULT '' COMMENT '參數(shù)',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

我們添加任務(wù)的時候不和quartz打交道,把任務(wù)放到數(shù)據(jù)庫即可。別慌,后面有用到他的地方。這個表需要有增刪改查操作,我們會在系統(tǒng)中查詢?nèi)蝿?wù)列表選擇單個或者所有任務(wù)開始執(zhí)行

執(zhí)行任務(wù)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Resource
 private QuartzJobMapper quartzJobMapper;
 @Autowired
 private Scheduler scheduler;
 
 
 @Override
 public String start(Integer id) {
 
        JobDataMap jobDataMap = new JobDataMap();
 jobDataMap.put(k,v);
 
 QuartzJob quartzJob = quartzJobMapper.selectByPrimaryKey(id);
 
 JobKey jobKey = JobKey.jobKey(quartzJob.getJobName(), quartzJob.getJobGroup());
 
 jobDetail = JobBuilder.newJob(TestJob.class).withIdentity(jobKey).storeDurably().build();
 
 Trigger trigger = TriggerComponent.cronTrigger(quartzJob.getCron(), jobDataMap);
 try {
  scheduler.scheduleJob(jobDetail, trigger);
  quartzJobMapper.updateStatus(true, id);
  return "開始任務(wù)執(zhí)行成功";
 } catch (SchedulerException se) {
  log.info("開始任務(wù)的時候發(fā)生了錯誤");
 }
 return "開始任務(wù)的時候發(fā)生了錯誤,請檢查日志";
 }

最后我又按照此教程上的內(nèi)容粘貼了一遍代碼,可以正常運(yùn)行。

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的代碼

到此這篇關(guān)于springboot+quartz以持久化的方式實(shí)現(xiàn)定時任務(wù)的文章就介紹到這了,更多相關(guān)springboot+quartz定時任務(wù)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://www.cnblogs.com/sxxs/p/13383929.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产在线一区二区三区 | 久久久www| 国产激情视频 | 午夜精品一区 | 欧美日韩欧美日韩 | 亚洲一区二区中文字幕 | 午夜视频一区 | 超碰在线人人草 | 国产女精品 | 国产一区二区三区免费在线观看 | 精品自拍视频在线观看 | 日韩福利二区 | 在线视频se | 欧美激情国产日韩精品一区18 | 国产欧美一区二区视频 | 91久久国产综合久久 | 久久噜噜噜精品国产亚洲综合 | 龙珠z国语版291集全 | 日韩操bb | 久久久一 | 精品视频一区二区三区在线观看 | 黄色片视频在线观看 | 亚洲天堂免费在线 | 国产一区二区视频在线 | 一本大道久久精品 | 欧美a级成人淫片免费看 | 亚洲激情在线视频 | 红杏首页 | 中文字幕精品一区 | 中文字幕高清视频 | 黄色片网站免费观看 | 色在线视频观看 | 欧美性久久 | 亚洲精品乱码 | 亚洲美女性视频 | 成人免费在线小视频 | 久久久免费视频看看 | 中文字幕在线免费看 | 免费国产一区 | 91精品一久久香蕉国产线看观看新通道出现 | 久久亚洲精品中文字幕 |