Detailed explanation of Java scheduled tasks and Java tasks
Scheduled tasks are often used in projects. This article describes the scheduled tasks based on the experience of the bloggers themselves:
1. Quartz scheduled task introduction and Quartz scheduled task configuration in Spring
2. SchedulerFactory adds, deletes, modifies, and queries scheduled tasks.
3. Summary
Quartz scheduled task introduction:
Quartz is one of the frequently-used scheduled tasks in projects. It is an open-source job scheduling framework fully compiled by java and can be used together with J2EE and J2SE applications, the main components include Job, schedpression, and CronExpression. We will not describe them one by one here. The following describes how to configure Quartz in Spring.
One thing you need to understand When configuring Quartz is to configure the Job, schedpression, and CronExpression. After these three parts are configured, it is a complete scheduled task. The configuration is as follows:
<Bean id = "TestJobDetail" class = "org. springframework. scheduling. quartz. JobDetailBean">
<Property name = "jobClass" value = "xx. TestQuartzJob"/>
<! -- Various data can be encapsulated into JobExecutionContext, including interfaces and classes. testServiceImpl is the Bean managed by Spring. What declaration is required? -->
<Property name = "jobDataAsMap">
<Map>
<Entry key = "test" value = "test"/>
<Entry key = "testServiceImpl" value-ref = "testServiceImpl"/>
</Map>
</Property>
</Bean>
<Bean id = "TestTrigger" class = "org. springframework. scheduling. quartz. CronTriggerBean">
<Property name = "jobDetail" ref = "TestJobDetail"/>
<Property name = "cronExpression" value = "0 0/1 ***? "/>
</Bean>
<Bean id = "testSchedulerFactoryBean" class = "org. springframework. scheduling. quartz. SchedulerFactoryBean">
<Property name = "triggers">
<List>
<Ref bean = "TestTrigger"/>
</List>
</Property>
</Bean>
<Bean id = "testServiceImpl" class = "xx. service. impl. TestServiceImpl">
After the configuration is complete, add a Java class to execute a task for you. Each Quartz Job must have a specific class that implements the org. quartz. Job interface. The Code is as follows:
Public class TestQuartzJob extends QuartzJobBean {
@ Override
Protected void executeInternal (JobExecutionContext arg0) throws JobExecutionException
{
// Obtain the Job configuration interface
TestServiceImpl testServiceImpl = (TestServiceImpl) arg0.getJobDetail (). getJobDataMap (). get ("testServiceImpl ");
// Execute the Business Method
QuartzStart ();
}
Public void quartzStart (){
// Business method...
}
}
Of course, you don't need to configure the interface specially in the Job, just use Spring injection. Here we will just describe the method of this configuration interface.
By now, the simple Quartz timing task has been configured. The following append a scenario where I use Quartz in the project: The cronExpression expression is read from the database.
At that time, I solved this problem by inheriting org. springframework. scheduling. quartz. CronTriggerBean and setting cronExpression. The specific code is as follows:
Modify the Trigger Configuration:
<Bean id = "TestTrigger" class = "xx. InitCronTriggerFactoryBean">
<Property name = "jobDetail" ref = "TestJobDetail"/>
<Property name = "key" value = "key"/>
</Bean>
Xx. InitCronTriggerFactoryBean code:
Public class InitCronTriggerFactoryBean extends CronTriggerFactoryBean implements Serializable {
Private static final long serialVersionUID = 1L;
@ Resource
Private SysParamService sysParamService;
Private String key;
Public void setKey (String key)
{
This. key = key;
SetCronExpression (getCronExpressionFromDB ());
}
Private String getCronExpressionFromDB ()
{
If (StringUtils. isEmpty (key ))
Return "0 0/5 ***? ";
SysParam sysParam = new SysParam ();
Try
{
SysParam = sysParamService. getNameByKey (key );
}
Catch (Exception e)
{
E. printStackTrace ();
}
If (sysParam! = Null &&! StringUtils. isEmpty (sysParam. getParamValue ()))
Return sysParam. getParamValue ();
Return "0 0/5 ***? ";
}
}
SysParamService is an interface for querying the corresponding cronExpression expression from the key to the database. In addition to Spring injection, you can also set this interface using the set method, as shown below:
<Bean id = "TestTrigger" class = "xx. InitCronTriggerFactoryBean">
<Property name = "jobDetail" ref = "TestJobDetail"/>
<Property name = "key" value = "key"/>
<Property name = "sysParamService" ref = "sysParamService"/>
</Bean>
<Bean id = "sysParamService" class = "xx. service. impl. SysParamServiceImpl">
In this way, the set Method of sysParamService will be added to xx. initcroggerfactorybean. The Code of xx. InitCronTriggerFactoryBean is as follows:
Public class InitCronTriggerFactoryBean extends CronTriggerFactoryBean implements Serializable {
Private static final long serialVersionUID = 1L;
Private SysParamServiceImpl sysParamService;
Private String key;
Public void setKey (String key)
{
This. key = key;
}
Public void setSysParamService (SysParamServiceImpl sysParamService)
{
This. sysParamService = sysParamService;
SetCronExpression (getCronExpressionFromDB ());
}
Private String getCronExpressionFromDB ()
{
If (StringUtils. isEmpty (key ))
Return "0 0 0/1 **? ";
SysParam sysParam = new SysParam ();
Try
{
SysParam = sysParamServiceImpl. getNameByKey (key );
}
Catch (Exception e)
{
E. printStackTrace ();
}
If (sysParam! = Null &&! StringUtils. isEmpty (sysParam. getParamValue ()))
Return sysParam. getParamValue ();
Return "0 0 0/1 **? ";
}
}
The Quartz timing task is almost done here. The basic configuration and usage are described above. If you want to learn more about Quartz, you can find more information on the Internet and use it in practice. Next, we will explain the instances used in the project that can add, delete, modify, and query scheduled tasks at any time.
The addition, deletion, modification, and query of scheduled tasks can be viewed as adding, deleting, modifying, and querying data. However, the addition, deletion, modification, and query operations of scheduled tasks are Job and Trigger operations. The specific code is as follows:
Code of the scheduled task manager:
Public class QuartzManager {
Private static final Logger logger = LogPresident. getRootLogger ();
Private static SchedulerFactory schedulerFactory = new StdSchedulerFactory ();
Private static Map <String, JobKey> jobKeyMap = new HashMap <String, JobKey> ();
/**
* Add a scheduled task
* @ Author zhiyuan. wu
* @ Date January 1, March 30, 2017
* @ Param jobName
* @ Param triggerName
* @ Param cls
* @ Param date
*/
@ SuppressWarnings ({"rawtypes", "unchecked "})
Public static void addJob (String jobName, String triggerName, Class cls, Date date)
{
Try
{
Scheduler schedfactory = schedulerFactory. getScheduler ();
// Job
JobDetail jobDetail = JobBuilder. newJob (cls). withIdentity (jobName, schedname. DEFAULT_GROUP). build ();
// Trigger
SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder. newTrigger (). withIdentity (triggerName, schedname. DEFAULT_GROUP). startAt (date). build ();
Scheduler. scheduleJob (jobDetail, trigger );
// Start
Scheduler. start ();
JobKeyMap. put (jobDetail. getKey (). getName (), jobDetail. getKey ());
}
Catch (Exception e)
{
Logger. error ("-------- add scheduled task error:" + e. getMessage (), e );
}
}
/**
* Delete the corresponding scheduled task
* @ Author zhiyuan. wu
* @ Date January 1, March 29, 2017
* @ Param jobKey
*/
Public static void removeJob (JobKey jobKey)
{
Scheduler scheduler;
Try
{
Scheduler = schedulerFactory. getScheduler ();
Schedjob. deleteJob (jobKey );
JobKeyMap. remove (jobKey. getName ());
}
Catch (SchedulerException e)
{
Logger. error ("-------- An error occurred while deleting the scheduled task:" + e. getMessage (), e );
}
}
/**
* Start all scheduled tasks
* @ Author zhiyuan. wu
* @ Date January 1, March 29, 2017
*/
Public static void startJobs ()
{
Try
{
Scheduler sched = schedulerFactory. getScheduler ();
Sched. start ();
}
Catch (Exception e)
{
Logger. error ("-------- error in starting all scheduled tasks:" + e. getMessage (), e );
}
}
/**
* Stop all scheduled tasks
* @ Author zhiyuan. wu
* @ Date January 1, March 29, 2017
*/
Public static void shutdownJobs ()
{
Try
{
Scheduler sched = schedulerFactory. getScheduler ();
If (! Sched. isShutdown ())
{
Sched. shutdown ();
}
}
Catch (Exception e)
{
Logger. error ("-------- stop all scheduled tasks error:" + e. getMessage (), e );
}
}
/**
* Modify a scheduled task
* @ Author zhiyuan. wu
* @ Date January 1, March 29, 2017
* @ Param jobKey
* @ Param jobName
* @ Param triggerName
* @ Param cls
* @ Param date
*/
@ SuppressWarnings ("rawtypes ")
Public static void modifyJobTime (JobKey jobKey, String jobName, String triggerName, Class cls, Date date)
{
Try
{
RemoveJob (jobKey );
AddJob (jobName, triggerName, cls, date );
}
Catch (Exception e)
{
Logger. error ("-------- error in modifying scheduled tasks:" + e. getMessage (), e );
}
}
/**
* Print the jobName of the current scheduled task
* @ Author zhiyuan. wu
* @ Date January 1, March 29, 2017
* @ Throws SchedulerException
*/
Public static void printJobName () throws SchedulerException
{
For (String jobName: jobKeyMap. keySet ())
{
Logger.info ("-------- jobName:" + jobName );
}
}
}
Job Code:
Public class TestJob implements Job {
Private static final Logger logger = LogPresident. getRootLogger ();
Public void execute (JobExecutionContext context) throws JobExecutionException
{
JobKey jobKey = context. getJobDetail (). getKey ();
Logger.info ("-------- scheduled task execution:" + jobKey. getName ());
// Business method...
// Remove a scheduled task
QuartzManager. removeJob (jobKey );
}
}
Add a scheduled task code:
QuartzManager. addJob (JobName, TriggerName, TestJob. class, Date );
In this way, the scheduled task will be executed when the Date is reached. However, the added task is saved in the memory, and the scheduled task will be lost when the project is restarted. Therefore, it is best to add a class that will scan the database when the project is started, reload unexecuted scheduled tasks to the memory.
The application of a scheduled task in a project needs to be adjusted according to the specific business. However, as long as the Principle and Implementation of the scheduled task are clarified, the task can be flexibly used for specific business in the project, I hope this article will allow you to quickly understand and use scheduled tasks and apply them to practice.