java--定时任务的实现方式

    xiaoxiao2021-03-25  79

    用java实现具体业务时,很多地方都要涉及到定时任务,比如说定时发送邮件、定时推送消息、定时抢购手机(这里我就想吐槽一下某米了)等。最近要用到这玩意儿,就研究了一下,大概有如下实现方式。

    1,使用ScheduledThreadPoolExecutor实现

    ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类。

    具体用法(每天0点执行new Runnable()进程):

     

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); Calendar calender = Calendar.getInstance(); calender.set(Calendar.HOUR, 0); calender.set(Calendar.MINUTE, 0); calender.set(Calendar.SECOND, 0); long delay = calender.getTimeInMillis() - System.currentTimeMillis(); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }, delay, 1, TimeUnit.DAYS);

     

    scheduleAtFixedRate方法的四个参数:

     

    command - the task to execute   要执行的任务

    initialDelay - the time to delay first execution  延迟一段时间执行第一次

    period - the period between successive executions  两次执行之间间隔时间

    unit - the time unit of the initialDelay and period parameters   时间单位

     

     

     

    2,使用Cron表达式实现

    转载请注明原文地址: https://ju.6miu.com/read-17949.html

    最新回复(0)