设置爬虫定时任务

一.导包



    org.quartz-scheduler
    quartz
    2.2.1

	


    org.quartz-scheduler
    quartz-jobs
    2.2.1

二.设置我们需要运行的任务(需要继承JOP接口)

package cn.itcast.spider.uitl;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

	/**
	 * 被定时执行的方法
	 */
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
			
		System.out.println(new Date().toString());
		
	}

}

三.设置任务器

public class CrontabSpider {
	public static void main(String[] args) throws SchedulerException {
			//获取调度工厂
		StdSchedulerFactory factory = new StdSchedulerFactory();
		//第二步:从调度工厂里面获取到一个可调度的对象
		Scheduler scheduler = factory.getScheduler();
		
		//设置任务
		JobDetail jobDetail = JobBuilder.newJob(MyJob.class).build();
		//设置触发器
		Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?")).build();	//调度对象设置时间并设置需要执行的任务第一个是对象,第二个是触发的时间
		scheduler.scheduleJob(jobDetail, trigger);
		//开始
		scheduler.start();
		
		
	}

}

四.运行结果

Fri May 18 18:35:40 CST 2018
Fri May 18 18:35:45 CST 2018
Fri May 18 18:35:50 CST 2018
Fri May 18 18:35:55 CST 2018
Fri May 18 18:36:00 CST 2018
Fri May 18 18:36:05 CST 2018
Fri May 18 18:36:10 CST 2018
Fri May 18 18:36:15 CST 2018

你可能感兴趣的:(设置爬虫定时任务)