# LsCron **Repository Path**: ranmc/ls-cron ## Basic Information - **Project Name**: LsCron - **Description**: Java定时任务小工具 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2021-01-21 - **Last Updated**: 2021-01-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # LsCron #### 介绍 Java定时任务小工具,适用于指定时间修改状态等场景 #### 软件架构 使用DeplayQueue延时队列实现 #### 安装教程 使用Maven安装,在发行版中下载Jar文件,使用mvn命令把Jar加入本地仓库,然后引用 ``` mvn install:install-file \ -DgroupId=org.ranmc \ -DartifactId=cron \ -Dversion=下载的Jar版本号 \ -Dpackaging=jar \ -Dfile=下载的Jar路径 ``` ``` org.ranmc cron 1.0 ``` #### 使用说明 创建任务类,实现LsDelayed接口 ``` package org.ranmc.cron; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; /** * @author Eric Ran * @since 2021/1/21 */ public class Task implements LsDelayed { /** * 任务名称 */ private final String name; /** * 执行时间戳 */ private final Long timestamp; public Task(String name, Long timestamp) { this.name = name; this.timestamp = timestamp; } public String getName() { return name; } /** * 返回值为<1开始执行 * * @param unit 时间单位 * @return <1 执行 */ public long getDelay(TimeUnit unit) { return timestamp - System.currentTimeMillis(); } public int compareTo(Delayed o) { return Long.compare(getDelay(TimeUnit.SECONDS), o.getDelay(TimeUnit.SECONDS)); } /** * 线程池执行 */ @Override public void run() { System.out.println(getName()); } } ``` 测试方法 ``` @Test public void test() { Task task1 = new Task("任务一", System.currentTimeMillis() + 1000); Task task2 = new Task("任务二", System.currentTimeMillis() + 2000); Task task3 = new Task("任务三", System.currentTimeMillis() + 3000); Task task4 = new Task("任务四", System.currentTimeMillis() + 1500); new CronDelayQueue() // 初始化任务 .init(() -> Arrays.asList(task1, task2, task3)) // 设置执行线程池 .setExecutor(new ThreadPoolExecutor(1, 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>())) // 部署任务队列,开始执行 .deploy() // 添加任务 .add(task4) // 移除任务 .remove(task3) // 阻塞主线程,实际业务中不需要 .block(); } ```