java实现定时任务

实例:实现每隔一小时打印语句

 

1.编写时间工具类

../Core/Util/TimerUtil.java

package ….Core.Util;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimerUtil {

	private ScheduledExecutorService scheduledExecutorService;

	/**
	 * @param runnable 方法
	 * @param time 延迟执行时间
	 * @param period 执行周期
	 */
	public void scheduleAtFixedRate(Runnable runnable,Long time,int period ){
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(runnable, time, period,TimeUnit.HOURS);//HOURS 间隔单位为小时;还有SECONDS秒、MINUTES分、DAYS天...
	}

	public void shutdown(){
		if(!scheduledExecutorService.isShutdown()){
			scheduledExecutorService.shutdown();
		}

	}
}

2.编写同步内容方法的工具类

../Core/Util/HttpUtil.java

package ….Core.Util;
import java.time.LocalDateTime;


public class HttpUtil {
	public String httpUrl(){
      
       //需要执行的方法

		String response = "";
		System.out.println("模拟定时同步数据接口: 时间 "+ LocalDateTime.now());
		return response;
	}

}

3.编写调用的控制类

方式一:开关控制

(需要调用接口进行任务启动或关闭,可自定义任务间隔时间)

    //开启定时任务
	@RequestMapping(value = "/openTimer")
	@ResponseBody
	public String openTimer(int period){
	            //period 自定义任务间隔时间
		//匿名方法
		Runnable runnable = () -> {
			HttpUtil httpUtil = new HttpUtil();
			httpUtil.httpUrl();
		};
		final long time = 1;//延迟执行实际:小时
		timerUtil = new TimerUtil();
		timerUtil.scheduleAtFixedRate(runnable,time,period);
		return "定时任务已开启!模拟数据变化频率:"+period+"小时";
	}

	//关闭定时任务
	@RequestMapping(value = "/shutdownTimer")
	@ResponseBody
	public String shutdownTimer(){
		timerUtil.shutdown();
		System.out.println("定时任务已关闭");
		return "定时任务已关闭";
	}

方式二:随项目部署启动后自动启动

//代码添加至默认会运行的控制器内
@PostConstruct
public void init(){
	System.out.println("定时任务 自动启动");
	int period = 1;
	Runnable runnable = () -> {
		HttpUtil httpUtil = new HttpUtil();
		httpUtil.httpUrl();
	};
	final long time = 1;//延迟执行实际:小时
	timerUtil = new TimerUtil();
	timerUtil.scheduleAtFixedRate(runnable,time,period);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值