本文共 3338 字,大约阅读时间需要 11 分钟。
在Java的ExecutorService中,scheduleAtFixedRate和scheduleWithFixedDelay是两个关键接口,用于实现定时任务的调度。理解这两个接口的区别对于优化应用性能至关重要。本文将深入探讨scheduleAtFixedRate的实现和应用。
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)方法定义了一个固定时间间隔的任务调度机制。其参数含义如下:
以下示例展示了如何使用scheduleAtFixedRate实现每隔100毫秒执行一次任务的定时调度:
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ScheduledExecutorServiceTest { public static void main(String[] args) { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate( new Runnable() { @Override public void run() { System.out.println("run " + System.currentTimeMillis()); } }, 0, // 初始化延时为0ms 100, // 每次执行间隔100ms TimeUnit.MILLISECONDS ); }} 运行上述代码,会看到每隔100ms输出一次“run”并带有当前时间戳。
在实际应用中,尤其是需要在特定时间点执行任务的情况下,可以通过scheduleAtFixedRate实现。例如,可以设置每天凌晨3点执行一次耗时较长的资源整理任务。
import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ExecutorTest { public static final ScheduledExecutorService service = Executors.newScheduledThreadPool(4); public static void main(String[] args) { long oneDay = 24 * 60 * 60 * 1000; // 一天的时间 long initDelay = getTimeMillis("03:00:00") - System.currentTimeMillis(); initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; service.scheduleAtFixedRate( new MyScheduled1(), initDelay, oneDay, TimeUnit.MILLISECONDS ); service.scheduleAtFixedRate( new MyScheduled2(), initDelay, oneDay, TimeUnit.MILLISECONDS ); } 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 (ParseException e) { e.printStackTrace(); } return 0; }}public class MyScheduled1 implements Runnable { @Override public void run() { System.out.println("my scheduled 01-----"); }}public class MyScheduled2 implements Runnable { @Override public void run() { System.out.println("my scheduled 02 ------"); }} scheduleWithFixedDelay与scheduleAtFixedRate的主要区别在于任务调度的机制:
这种区别使得scheduleAtFixedRate适用于需要严格按照固定时间间隔执行任务的场景,而scheduleWithFixedDelay则适用于任务执行时间不确定的场景。
通过本文的分析,可以看出scheduleAtFixedRate是一个强大的工具,适用于需要在固定时间间隔内执行任务的场景。在实际应用中,可以根据任务的执行需求选择合适的调度接口,以优化资源利用率和应用性能。
转载地址:http://xybe.baihongyu.com/