Three Ways to Realize Timing Task in JAVA

Keywords: Spring JDK SpringBoot

Links to the original text: https://www.w3cschool.cn/quartz_doc/

Catalog

1. TimerTask with JDK

2. Use third-party packages: QuartZ Suitable for particularly complex business

3. Timing Task Management with Spring This is usually enough.

1. TimerTask with JDK

[Understanding] https://www.cnblogs.com/0201zcr/p/4703061.html

For Example:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("11232");
        }
}, 2000 , 1000);

Start execution after 2s, once per second

2. Use third-party packages: QuartZ

[Familiar with, single class tests pass, but integration into SSM/SpringBook has not been studied successfully]

 https://www.w3cschool.cn/quartz_doc/

For Example:

(1) Importing POM dependencies:

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.3.0</version>
</dependency>

(2) Tool class QuartzManager

public class QuartzManager {  
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  //Create a Scheduler Factory instance
    private static String JOB_GROUP_NAME = "JOB_GROUP_1";  				//Task Force
    private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_1";  			//Flip-flop group
  
    /**
    *Add a timed task.
    */
    public static void addJob(String jobName, Class<? extends Job> cls, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  										
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();	
        	CronTrigger trigger = (CronTrigger) TriggerBuilder
        			.newTrigger()	 																	
    				.withIdentity(jobName, TRIGGER_GROUP_NAME)											
    				.withSchedule(CronScheduleBuilder.cronSchedule(time))
    				.build();
            sched.scheduleJob(jobDetail, trigger);  
            if (!sched.isShutdown()) {  
                sched.start();  	  // start-up  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

}

(3) Job class HelloJob

public class HelloJob implements Job {

    public HelloJob() {
    }

    public void execute(JobExecutionContext context) throws JobExecutionException
    {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
      System.out.println("Hello!  HelloJob is executing."+df.format(new Date()));
    }


}

(4) Test QuartZ

public class testQuartZ {
 
	public static void main(String[] args) throws HttpException, IOException {
		   
		QuartzManager.addJob("Demo", HelloJob.class, "0/5 * * * * ?");
	
	}
}

(5) Running test class, the effect is as follows

3. Timing Task Management with Spring

[In use]

3.1, Spring Implementation of Timing Tasks in SSM

3.2. SpringBoot annotations for timing tasks (SpringBoot 2.X)

(1) Startup class add annotation @EnableScheduling

(2) Adding annotation @Component to the class is scanned by the container

(3) The method that needs to be executed regularly is annotated @Scheduled(fixedRate = 2000), which is executed every 2 seconds.

@Component
public class testTask {
    @Scheduled(fixedRate = 2000)
    public void test(){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Hello!  HelloJob is executing."+df.format(new Date()));
    }
}

Posted by Sherman on Wed, 09 Oct 2019 01:20:58 -0700