编程语言
首页 > 编程语言> > java 定时任务quartz-1.5.2.jar 超简单使用

java 定时任务quartz-1.5.2.jar 超简单使用

作者:互联网

1)引入依赖

<!-- https://mvnrepository.com/artifact/quartz/quartz -->
<dependency>
    <groupId>quartz</groupId>
    <artifactId>quartz</artifactId>
    <version>1.5.2</version>
</dependency>

2)编写定时要完成的工作(这里有个简单的HTTP请求)

package  demo;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TestJob implements Job {

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    System.out.println("下次执行时间为:" +jobExecutionContext.getNextFireTime());
    try {
      req();
    } catch (UnirestException e) {
      e.printStackTrace();
    }
  }

  private void req() throws UnirestException {
    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response =
        Unirest.get("http://127.0.0.1:8080/").header("Cookie", "Cookie_1=value").asString();
    System.out.println("response = " + response.getStatusText());
  }

}

quartz定时任务三板斧

package demo;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.ParseException;

public class CrontabForJava {
  public static void main(String[] args) throws ParseException {
      // 1)定时做什么任务
      JobDetail jobDetail = new JobDetail("name", "group", TestJob.class); // 任务名,任务组,任务执行类
      // 2) Trigger 什么时候去做
      Trigger trigger2 = null;
      // trigger2 = new SimpleTrigger("name", "group");
      trigger2 = new CronTrigger("name","group", "0 */1 * * * ?");//和linux Crontab 不同 是从秒开始的

      // 3) Scheduler 任务调度 你什么时候需要去做什么事
      Scheduler sch;
      try {
          sch = StdSchedulerFactory.getDefaultScheduler();
          sch.scheduleJob(jobDetail, trigger2);
          sch.start();
      } catch (SchedulerException e) {
          e.printStackTrace();
      }
  }
}

标签:1.5,quartz,java,sch,trigger2,import,org,public
来源: https://www.cnblogs.com/xmc000/p/15195744.html