定时线程池ScheduledExecutorService
ScheduledExecutorService接口列表:
scheduleAtFixedRate方法定义及参数说明
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
- command:执行线程;
- initialDelay:初始化延时;
- period:两次开始执行最小间隔时间;
- unit:计时单位;
使用scheduleAtFixedRate()方法实现周期性执行
如:每隔100毫秒,执行一次run任务,得到执行后的打印:
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, 100, TimeUnit.MILLISECONDS);
}
}
使用scheduleAtFixedRate()方法实现周期性定时任务
有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。
public class ScheduledExecutorServiceTest {
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);
}
/**
* 获取指定时间对应的毫秒数
*
* @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 (ParseException e) {
e.printStackTrace();
}
return 0;
}
public static class MyScheduled1 implements Runnable {
@Override
public void run() {
System.out.println("my scheduled 01-----");
}
}
public static class MyScheduled2 implements Runnable {
@Override
public void run() {
System.out.println("my scheduled 02 ------");
}
}
}
scheduleWithFixedDelay方法定义及参数说明
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
- command:执行线程
- initialDelay:初始化延时
- period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
- unit:计时单位
scheduleAtFixedRate 是基于固定时间间隔进行任务调度,scheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现