Cron Job (Scheduler)

Sometimes we need to run a class after a specific time again and again.
we can called this say scheduler. wow, so it can run after a periodic time.
suppose everyday at 10 pm we need to send email to our registered consumers.
so we need to run our MailSend class file ( assume ) everyday at 10pm.
it's just an scenario. in java this is called cron job.
we can achieve this by
1) using quartz scheduler.
2) using cron4j.
3) using spring jar. etc

whatever, we can use any of them. here i used quartz scheduler. to use it, first download the stable version of quartz jar from here. then add it to your class path.
suppose i have a class that is for just to connect the database.
this class i want to run after 10 sec again and again. the class is given below,

1:  import java.io.FileInputStream;  
2:  import java.io.FileNotFoundException;  
3:  import java.io.IOException;  
4:  import java.io.InputStream;  
5:  import java.sql.Connection;  
6:  import java.sql.DriverManager;  
7:  import java.sql.SQLException;  
8:  import java.util.Properties;  
9:  import org.quartz.Job;  
10:  import org.quartz.JobExecutionContext;  
11:  import org.quartz.JobExecutionException;  
12:  /**  
13:   *  
14:   * @author Ataur Rahman  
15:   */  
16:  public class ReportScheduler implements Job {  
17:    public ReportScheduler() throws IOException, ClassNotFoundException, SQLException {  
18:  //    System.out.println("this is from scheduler call");  
19:      String result = getDBQuery();  
20:      System.out.println("connection is "+ result);  
21:    }  
22:    @Override  
23:    public void execute(JobExecutionContext jec) throws JobExecutionException {  
24:      throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.  
25:    }  
26:    public static Properties getSchedulerProperties() throws FileNotFoundException, IOException{  
27:      String fileSystemFileLoc = "D:/dbproperties.properties";  
28:      Properties prop = new Properties();  
29:      InputStream is =new FileInputStream(fileSystemFileLoc);  
30:      if (is != null) {  
31:        prop.load(is);  
32:      } else {  
33:        throw new FileNotFoundException("DB properties file not found");  
34:      }  
35:      return prop;  
36:    }  
37:    public static String getDBQuery() throws IOException, ClassNotFoundException, SQLException {  
38:      Properties prop = new Properties();  
39:      prop = getSchedulerProperties();  
40:      String host = prop.getProperty("host");  
41:      String port = prop.getProperty("port");  
42:      String userName = prop.getProperty("username");  
43:      String password = prop.getProperty("password");  
44:      String dbName = prop.getProperty("dbName");  
45:      Class.forName("org.postgresql.Driver");  
46:      Connection connection = null;  
47:      try {  
48:        connection = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/" + dbName, userName, password);  
49:      } catch (Exception e) {  
50:        e.printStackTrace();  
51:      }  
52:      if (connection != null) {  
53:        System.out.println("connected successfully");  
54:        connection.close();  
55:        return "success";  
56:      }  
57:      else return "not success";  
58:    }  
59:  }  
the important thing is which class i want to run also implements the interface Job. ow.. ow.. the properties file was missing, and of course don't forget to change your properties file location if you used of your own. :D

here is the properties file given below,

1:  # To change this template, choose Tools | Templates  
2:  # and open the template in the editor.  
3:  host=192.##.##.##  
4:  port=9999  
5:  username=root  
6:  password=  
7:  dbName=your_db_name_here  
8:  cronExpression = 0/10 * * * * ?  
here you can edit anything depending of your need.

we can set our time using cronExpression in properties file or can use:

1:   SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever();  
2:      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();  
 here i used cron Expression. now the main class is given below:

1:  import java.io.IOException;  
2:  import java.util.Properties;  
3:  import org.quartz.CronScheduleBuilder;  
4:  import org.quartz.Scheduler;  
5:  import org.quartz.SchedulerException;  
6:  import org.quartz.SchedulerFactory;  
7:  import org.quartz.Trigger;  
8:  import org.quartz.TriggerBuilder;  
9:  import org.quartz.impl.JobDetailImpl;  
10:  import org.quartz.impl.StdSchedulerFactory;  
11:  /**  
12:   *  
13:   * @author Ataur Rahman  
14:   */  
15:  public class RunJob {  
16:    public RunJob() {  
17:    }  
18:    public static void main(String args[]) throws SchedulerException, IOException, ClassNotFoundException {  
19:      SchedulerFactory scheduleFactory = new StdSchedulerFactory();  
20:      Scheduler scheduler = scheduleFactory.getScheduler();  
21:      JobDetailImpl jobDetail = new JobDetailImpl();  
22:      jobDetail.setName("First_Job");  
23:      jobDetail.setGroup("CRON_SCHEDULER");  
24:      System.out.println("job detail group = " + jobDetail.getGroup());  
25:      jobDetail.setJobClass(ReportScheduler.class);  
26:      Properties prop = new Properties();  
27:      prop = ReportScheduler.getSchedulerProperties();  
28:      String cronExpression = prop.getProperty("cronExpression");  
29:      System.out.println("Cron Expression now = " + cronExpression);  
30:      //SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever();  
31:      //Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();  
32:      Trigger trigger = null;  
33:      if (cronExpression != null && !cronExpression.equals("")) {  
34:        trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();  
35:      }  
36:      scheduler.start();  
37:      scheduler.scheduleJob(jobDetail, trigger);  
38:    }  
39:  }  

the RunJob  class can run the ReportScheduler class after 10 sec again and again.
pretty cool huh, enjoy coding. :D

Comments

Popular posts from this blog

UUID to BigInteger conversion and BigInteger to UUID conversion

ActiveMQ message producer and consumer with durable subscriber example

Create Maven Local Repository, Upload your own artifact & download jar from local mirror with Artifactory and Nexus OSS