In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces SpringBoot2 integration QuartJob how to achieve timer real-time management function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
A brief introduction to QuartJob
1. One-sentence description
Quartz is an open source job scheduling framework written entirely by java, which is simple and powerful.
2. Core API
(1), Scheduler
Representing a stand-alone running container of Quartz, Scheduler binds the Trigger to a specific JobDetail so that when the Trigger is triggered, the corresponding Job is scheduled.
(2), Trigger
Describes the time-triggered rules that Job executes. There are mainly two subclasses, SimpleTrigger and CronTrigger, which are uniquely identified by a TriggerKey.
(3), Job
Define a task that specifies the behavior of the task when it is executed. JobExecutionContext provides context information for the scheduler, and data for Job can be obtained from JobDataMap.
(4), JobDetail
Quartz recreates an instance of Job each time it executes Job, so instead of accepting an instance of Job directly, it receives a Job implementation class. Describe the implementation class of Job and other related static information, such as Job name, description, etc.
II. Integration with SpringBoot2.0
1. Project structure
Version description
Spring-boot:2.1.3.RELEASEquart-job:2.3.0
2. Timer configuration
Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.quartz.SchedulerFactoryBean;import javax.sql.DataSource;import java.util.Properties;@Configurationpublic class ScheduleConfig {@ Bean public SchedulerFactoryBean schedulerFactoryBean (DataSource dataSource) {/ / Quartz parameter configuration Properties prop = new Properties (); / / entity name of the Schedule scheduler prop.put ("org.quartz.scheduler.instanceName", "HuskyScheduler") / / when set to AUTO, the default implementation org.quartz.scheduler.SimpleInstanceGenerator is generated based on the host name and timestamp. Prop.put ("org.quartz.scheduler.instanceId", "AUTO"); / / Thread pool configuration prop.put ("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); prop.put ("org.quartz.threadPool.threadCount", "20"); prop.put ("org.quartz.threadPool.threadPriority", "5") / / JobStore configuration: Scheduler is used to store related information at run time / / both JDBCJobStore and JobStoreTX use relational databases to store Schedule-related information. / / JobStoreTX uses commit or rollback to commit changes after each task. Prop.put ("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); / / Cluster configuration: if there are multiple scheduler entities, it must be set to true prop.put ("org.quartz.jobStore.isClustered", "true"); / / Cluster configuration: check the interval prop.put of other scheduler entities under the cluster ("org.quartz.jobStore.clusterCheckinInterval", "15000"). / / set a frequency (milliseconds) for instances to report to other instances in the cluster prop.put ("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); / / interval between prop.put ("org.quartz.jobStore.misfireThreshold", "12000") after trigger failure; / / database table prefix prop.put ("org.quartz.jobStore.tablePrefix", "qrtz_") / / SQL statement prop.put that queries a row from the LOCKS table and locks the row ("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0} LOCKS UPDLOCK WHERE LOCK_NAME =?"); / / timer factory configuration SchedulerFactoryBean factory = new SchedulerFactoryBean (); factory.setDataSource (dataSource); factory.setQuartzProperties (prop); factory.setSchedulerName ("HuskyScheduler"); factory.setStartupDelay (30); factory.setApplicationContextSchedulerContextKey ("applicationContextKey") / / optionally, update the existing Job factory.setOverwriteExistingJobs (true) when QuartzScheduler starts; / / set automatic startup. Default is true factory.setAutoStartup (true); return factory;}}
3. Timer management tools
Import com.quart.job.entity.ScheduleJobBean;import org.quartz.*;/** * timer tool class * / public class ScheduleUtil {private ScheduleUtil () {} private static final String SCHEDULE_NAME = "HUSKY_"; / * trigger KEY * / public static TriggerKey getTriggerKey (Long jobId) {return TriggerKey.triggerKey (SCHEDULE_NAME+jobId);} / * timer Key * / public static JobKey getJobKey (Long jobId) {return JobKey.jobKey (SCHEDULE_NAME+jobId) } / * expression trigger * / public static CronTrigger getCronTrigger (Scheduler scheduler,Long jobId) {try {return (CronTrigger) scheduler.getTrigger (getTriggerKey (jobId));} catch (SchedulerException e) {throw new RuntimeException ("getCronTrigger Fail", e) }} / * create timer * / public static void createJob (Scheduler scheduler, ScheduleJobBean scheduleJob) {try {/ / build timer JobDetail jobDetail = JobBuilder.newJob (TaskJobLog.class) .withIdentity (getJobKey (scheduleJob.getJobId ()). Build (); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder .cronSchedule (scheduleJob.getCron_Expression ()). WithMisfireHandlingInstructionDoNothing (); CronTrigger trigger = TriggerBuilder.newTrigger () .withIdentity (getTriggerKey (scheduleJob.getJobId () .withschedule (scheduleBuilder). Build () JobDetail.getJobDataMap () .put (ScheduleJobBean.JOB_PARAM_KEY,scheduleJob); scheduler.scheduleJob (jobDetail,trigger); / / if the timer is paused if (scheduleJob.getStatus () = = 1) {pauseJob (scheduler,scheduleJob.getJobId ());}} catch (SchedulerException e) {throw new RuntimeException ("createJob Fail", e) }} / * Update scheduled tasks * / public static void updateJob (Scheduler scheduler, ScheduleJobBean scheduleJob) {try {/ / build timer TriggerKey triggerKey = getTriggerKey (scheduleJob.getJobId ()); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule (scheduleJob.getCron_Expression ()) .withMisfireHandlingInstructionDoNothing (); CronTrigger trigger = getCronTrigger (scheduler, scheduleJob.getJobId ()); trigger = trigger.getTriggerBuilder (). WithIdentity (triggerKey) .withschedule (scheduleBuilder). Build (); trigger.getJobDataMap (). Put (ScheduleJobBean.JOB_PARAM_KEY, scheduleJob) Scheduler.rescheduleJob (triggerKey, trigger); / / if the timer is paused if (scheduleJob.getStatus () = = 1) {pauseJob (scheduler, scheduleJob.getJobId ());}} catch (SchedulerException e) {throw new RuntimeException ("updateJob Fail", e);}} / * * stop timer * / public static void pauseJob (Scheduler scheduler,Long jobId) {try {scheduler.pauseJob (getJobKey (jobId)) } catch (SchedulerException e) {throw new RuntimeException ("pauseJob Fail", e);}} / * recovery timer * / public static void resumeJob (Scheduler scheduler,Long jobId) {try {scheduler.resumeJob (getJobKey (jobId));} catch (SchedulerException e) {throw new RuntimeException ("resumeJob Fail", e);}} / * delete timer * / public static void deleteJob (Scheduler scheduler,Long jobId) {try {scheduler.deleteJob (getJobKey (jobId)) } catch (SchedulerException e) {throw new RuntimeException ("deleteJob Fail", e);}} / * execute timer * / public static void run (Scheduler scheduler, ScheduleJobBean scheduleJob) {try {JobDataMap dataMap = new JobDataMap (); dataMap.put (ScheduleJobBean.JOB_PARAM_KEY,scheduleJob); scheduler.triggerJob (getJobKey (scheduleJob.getJobId ()), dataMap);} catch (SchedulerException e) {throw new RuntimeException ("run Fail", e);}
4. Timer execution and log
Import com.quart.job.entity.ScheduleJobBean;import com.quart.job.entity.ScheduleJobLogBean;import com.quart.job.service.ScheduleJobLogService;import org.quartz.JobExecutionContext;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.quartz.QuartzJobBean;import java.lang.reflect.Method;import java.util.Date;/** * timer executes logging * / public class TaskJobLog extends QuartzJobBean {private static final Logger LOG = LoggerFactory.getLogger (TaskJobLog.class) @ Override protected void executeInternal (JobExecutionContext context) {ScheduleJobBean jobBean = (ScheduleJobBean) context.getMergedJobDataMap () .get (ScheduleJobBean.JOB_PARAM_KEY); ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtil.getBean ("scheduleJobLogService"); / / timer logging ScheduleJobLogBean logBean = new ScheduleJobLogBean (); logBean.setJobId (jobBean.getJobId ()); logBean.setBeanName (jobBean.getBeanName ()); logBean.setParams (jobBean.getParams ()); logBean.setCreateTime (new Date ()); long beginTime = System.currentTimeMillis () Try {/ / run method for loading and executing timers Object target = SpringContextUtil.getBean (jobBean.getBeanName ()); Method method = target.getClass (). GetDeclaredMethod ("run", String.class); method.invoke (target, jobBean.getParams ()); long executeTime = System.currentTimeMillis ()-beginTime; logBean.setTimes ((int) executeTime); logBean.setStatus (0); LOG.info ("timer = > >" + jobBean.getJobId () + "executed successfully, time = = > >" + executeTime) } catch (Exception e) {/ / exception information long executeTime = System.currentTimeMillis ()-beginTime; logBean.setTimes ((int) executeTime); logBean.setStatus (1); logBean.setError (e.getMessage ());} finally {scheduleJobLogService.insert (logBean);}
Third, timer service encapsulation
1. Timer initialization
@ Servicepublic class ScheduleJobServiceImpl implements ScheduleJobService {@ Resource private Scheduler scheduler; @ Resource private ScheduleJobMapper scheduleJobMapper; / * * timer initialization * / @ PostConstruct public void init () {ScheduleJobExample example = new ScheduleJobExample (); List scheduleJobBeanList = scheduleJobMapper.selectByExample (example); for (ScheduleJobBean scheduleJobBean: scheduleJobBeanList) {CronTrigger cronTrigger = ScheduleUtil.getCronTrigger (scheduler,scheduleJobBean.getJobId ()); if (cronTrigger = = null) {ScheduleUtil.createJob (scheduler,scheduleJobBean);} else {ScheduleUtil.updateJob (scheduler,scheduleJobBean);}}
2. Add a timer
@ Override@Transactional (rollbackFor = Exception.class) public int insert (ScheduleJobBean record) {ScheduleUtil.createJob (scheduler,record); return scheduleJobMapper.insert (record);}
3. Execute a timer immediately
@ Override@Transactional (rollbackFor = Exception.class) public void run (Long jobId) {ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey (jobId); ScheduleUtil.run (scheduler,scheduleJobBean);}
4. Update timer
@ Override@Transactional (rollbackFor = Exception.class) public int updateByPrimaryKeySelective (ScheduleJobBean record) {ScheduleUtil.updateJob (scheduler,record); return scheduleJobMapper.updateByPrimaryKeySelective (record);}
5. Stop the timer
@ Override@Transactional (rollbackFor = Exception.class) public void pauseJob (Long jobId) {ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey (jobId); ScheduleUtil.pauseJob (scheduler,jobId); scheduleJobBean.setStatus (1); scheduleJobMapper.updateByPrimaryKeySelective (scheduleJobBean);}
6. Recovery timer
@ Override@Transactional (rollbackFor = Exception.class) public void resumeJob (Long jobId) {ScheduleJobBean scheduleJobBean = scheduleJobMapper.selectByPrimaryKey (jobId); ScheduleUtil.resumeJob (scheduler,jobId); scheduleJobBean.setStatus (0); scheduleJobMapper.updateByPrimaryKeySelective (scheduleJobBean);}
7. Delete timer
@ Override@Transactional (rollbackFor = Exception.class) public void delete (Long jobId) {ScheduleUtil.deleteJob (scheduler, jobId); scheduleJobMapper.deleteByPrimaryKey (jobId);}
Fourth, configure a test timer
1. Timing interface encapsulation
Public interface TaskService {void run (String params);}
2. Test timer
@ Component ("getTimeTask") public class GetTimeTask implements TaskService {private static final Logger LOG = LoggerFactory.getLogger (GetTimeTask.class.getName ()); private static final SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); @ Override public void run (String params) {LOG.info ("Params = >" + params); LOG.info ("current time:" + format.format (new Date ();}}
Thank you for reading this article carefully. I hope the article "SpringBoot2 Integration QuartJob how to achieve timer Real-time Management function" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.