Thursday, September 15, 2016

Scheduling a Job using spring

Requirement:

We have to send email on a regular interval by checking a condition automatically.

Solution:
We can use Queartz Job scheduler which is an open source job scheduling library and can be attached with any java application.

Alternatively we can use Spring's Task scheduler using TaskScheduler and TaskExecutor.

Pros:

  • This approach is good for the situation where you are already using Spring in code. 
  • Its quick and easy to implement.
  • You do not have many jobs to run.


To implement the spring way we should use @EnableScheduling annotation in our AppConfig.java
The above annotation enables Spring's scheduled task execution capability.

Below is an example which gets executed every hours and prints the current time.


 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
package blogspot.thinkwithjava;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 *
 * @author R.D
 *
 */
@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "0 0 0/1 1/1 * ?")
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}


cron = "0 0 0/1 1/1 * ?"

To schedule a task we provide a cron pattern as mentioned above. The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.

Cron pattern for every Five Minute

"0 0/5 * 1/1 * ?"

Cron pattern for every hour

 "0 0 0/1 1/1 * ?"

Cron pattern for every four hour

"0 0 0/4 1/1 * ?"

More information is given here.

No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...