quartz的简单调用

来源:互联网 发布:java udp收数据不全 编辑:程序博客网 时间:2024/05/21 07:49

有一个对应用程序爬数据的任务,但是不是一个劲地运行,而是想按计划地每隔一小时运行一次,发现了一个开源的java架构挺好用的,就是quartz。
首先在下面网站下载quartz的jar包,把所有的都导入到程序中去。

http://www.quartz-scheduler.org/

然后就能开始编程了。
如果你的任务已经是一个单独的程序,在里面再加一个新的作为main函数然后来运行吧,下面是代码:

public class quartzTest {    public static void main(String args[]) throws SchedulerException, ParseException {        JobDetail jobDetail= JobBuilder.newJob(BluedXYGET2.class)                .withIdentity("testJob_1","group_1")                .build();        Date runTime = DateBuilder.dateOf(0, 0, 0, 7, 8);        Trigger trigger= TriggerBuilder                .newTrigger()                .withIdentity("trigger_1","group_1")                .startNow()                .withSchedule(SimpleScheduleBuilder.simpleSchedule()                        .withIntervalInHours(1)//                        .withIntervalInSeconds(10) //时间间隔                        .withRepeatCount(24)//                        .withRepeatCount(3)        //重复次数(将执行6次)                        )                .startAt(runTime)                .build();        SchedulerFactory sf = new StdSchedulerFactory();        Scheduler sched = sf.getScheduler();        sched.scheduleJob(jobDetail,trigger);         sched.start();     }}

代码应该很清楚的,具体的一些触发参数可以看看解释,应该也一目了然。
当然你的原程序当然得修改了

public class BluedXYGET2 implements Job

要实现quartz里面的接口

@Override    public void execute(JobExecutionContext context)            throws JobExecutionException {            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        SimpleDateFormat saveFormatter = new SimpleDateFormat("MM-dd-HH-mm");        Date startTime = new Date();                String sTime = formatter.format(startTime);        String saveName = saveFormatter.format(startTime);        mXYPath = "E:\\" + saveName + ".txt";        save(sTime, mXYPath);        System.out.println(sTime);        xyCrawler();        Date endTime = new Date();        String eTime = formatter.format(endTime);        save(eTime, mXYPath);    }

把原来main里面运行的任务移到这个执行函数里面就行了,很简单吧。

0 0
原创粉丝点击