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());
  }

}

3)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();
      }
  }
}

 Note: This artifact was moved to:

Home » org.quartz-scheduler » quartz

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值