定时任务,Java(二)

 
public class SimpleQuartzJob implements Job{
 
    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        String key = "hello1";
        String value = (String)arg0.getJobDetail().getJobDataMap().get(key);
        System.out.println("key is " + key + ", value is " + value);
    }
 
}



public class Main {
    private Scheduler scheduler;
    
    public void task() throws SchedulerException
    {
        try {
            // Initiate a Schedule Factory
            if (DirectSchedulerFactory.getInstance().getAllSchedulers().isEmpty()) {
                DirectSchedulerFactory.getInstance().createVolatileScheduler(5);
            }
            // Retrieve a scheduler from schedule factory
            this.scheduler = DirectSchedulerFactory.getInstance().getScheduler();
        }
        catch (final SchedulerException e) {
            System.out.println("scheduler构造出错");
        }
        
        
        // Initiate JobDetail with executable job class
        JobDetail jobDetail = newJob(SimpleQuartzJob.class).build();
        jobDetail.getJobDataMap().put("hello1", "value1");
        // Initiate Trigger with an expression 
        Trigger trigger = newTrigger().withSchedule(cronSchedule("0/5 * * * * ?")).forJob(jobDetail).build();
        
        this.scheduler.start();
        this.scheduler.scheduleJob(jobDetail, trigger);
        
    }
    
 
    public static void main(String[] args){
 
        Main o = new Main();
        try {
            o.task();
        } catch (SchedulerException e) {
            System.out.println("main()函数出错");
        }
    }
 
}
posted @ 2012-06-05 14:17  技术草根女  Views(510)  Comments(0Edit  收藏  举报