博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java时时调度(一)
阅读量:4262 次
发布时间:2019-05-26

本文共 2381 字,大约阅读时间需要 7 分钟。

      这几天在做项目的时候遇到一个问题,那就是如何做到时时监控。当时因为一些事情没有做。后来换了一个项目,关于支付系统中的对账,要做时时对账,呵呵,出来混总是要还的。今天我们就来看一个小例子来实现时时调度。

一、时时任务

1、控制类

public class timeTest {
/** * 时时调度 * 3秒后开始,每隔1秒打印一次 */ public static void executePerDay() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); System.out.println("时时调度"); //打印当前时间 System.out.println("getTest()"+ new Date().toString()); executor.scheduleAtFixedRate( new payTest(), //调用执行方法的类 3000, //初始化延迟3秒 1000, //每隔1秒执行一次 TimeUnit.MILLISECONDS); } }

2、正真执行者

public class payTest implements Runnable {
@Override public void run() { //打印当前时间 System.out.println("getTest()"+ new Date().toString()); }}

3、主类

public class mainTest {    public static void main(String[] args)  {        timeTest test = new timeTest();        //时时调度        test.executePerDay();    }}

      看上去很简单吧,其实也就这么简单,接下来我们做一下变形,做一个定时执行的小例子。

二、定时任务

1、控制类

public class timeTest {
/** * 时时调度 * 3秒后开始,每隔1秒打印一次 */ public static void executePerDay() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); long oneDay = 24 * 60 * 60 * 1000; //计算时间间隔 long initDelay = getTimeMillis("14:46:14") - System.currentTimeMillis(); //判断当天的执行时间是否已过,如果已过,需要等到第二天执行 initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; System.out.println("时时调度"); System.out.println("getTest()"+ new Date().toString()); executor.scheduleAtFixedRate( new payTest(), //调用执行方法的类 initDelay, //初始化延迟 oneDay, //每隔多久执行一次 TimeUnit.MILLISECONDS); } /** * 获取指定时间对应的毫秒数 * @param time "HH:mm:ss" * @return */ private static long getTimeMillis(String time) { try { //格式化时间 DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd"); Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time); return curDate.getTime(); } catch (Exception e) { e.printStackTrace(); } return 0; } }

总结:

      这样我们通过ScheduledExecutorService 类,就实现了时时调度,至于它的运行机理,还有解析等,我会在下篇博客中给大家分享。

转载地址:http://gumei.baihongyu.com/

你可能感兴趣的文章
CentOS6.5系统挂载NTFS分区的移动硬盘
查看>>
SecureCRT 实现文件的上传与下载 sz 和rz
查看>>
centos 关机和重启命令详解
查看>>
centos 下安装rar
查看>>
mysql数据库远程访问设置方法
查看>>
CentOS 6 时间,时区,设置修改及时间同步
查看>>
tar 命令使用详解
查看>>
ubuntu13.04使用root账号登陆
查看>>
linux 实现共享文件共享
查看>>
排序算法之归并排序
查看>>
白话https加密原理
查看>>
Android Flutter windows版 第一个程序运行
查看>>
Java基础--定时任务Timer
查看>>
GreenDao 3.2.2 使用总结
查看>>
Android打包 android.support.v4.content.FileProvider冲突
查看>>
Mina框架在项目中的使用(一)
查看>>
MINA2.0 原理
查看>>
mina Connection reset by peer异常
查看>>
Apache Mina Server 2.0 中文参考手册
查看>>
java.lang.RuntimeException: Manifest merger failed with multiple errors, see logs
查看>>