Jobs scheduling

This framework bundels the well known quartz job scheduling framework. Building such jobs is very easy. Actually you only have to extend the class AbstractJob and place your class in a special package. Then the jobs will be picked up automatically during startup and will be set up.

Writing a scheduled job

First you need to create a new class. If not already existing create a subpackage called jobs within your basepackage. The framework will check this package when starting up and picking up all classes that extends the AbstractJob class automatically. There is no need to register your job or anything else. Such a class needs to look like this:

import org.jzonic.jobs.AbstractJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyScheduledJob extends AbstractJob {

public void execute(JobExecutionContext context) throws JobExecutionException { .... // do your stuff here }

public String getCronExpression() { // for example every day at 17:30 return "0 30 17 * * ?"; }

public String getName() { return "MyScheduledJob"; } }

First the getName must return the name of your job. That can be any name. The job will be referenced in the scheduler by this name. Then the getCronExpression method must returns a cron expression. This expression defines when or how often your job will be executed. Last the execute will be called when your job is scheduled.

Of course here you also have access to the ApplicationContext and therefore also to registered beans. So you can do something like this:

public void execute(JobExecutionContext context) throws JobExecutionException {
  UserDAO userDAO = (UserDAO)ApplicationContext.getBean(UserDAO.class);
  List oldUsers = userDAO.getAllUsersToDelete();
  for ( Iterator it = oldUsers.iterator();it.hasNext();) {
    User user = (User)it.next();
    userDAO.deleteUser(user);
  }
}

This is probably not a clever example but just demonstrates how easily you can access DAOs.

Page: ScheduledJobs last edited by admin on 03/24/2009 21:45 revision: 0
Labels:  (none)    Permalink