如何在Java中实现日程提醒工具

定义包含标题、描述和提醒时间的ScheduleTask类;2. 使用ScheduledExecutorService按延迟时间调度任务;3. 通过main方法添加多个测试提醒,程序在指定时间输出提示信息,并注意时间单位转换与资源释放。

在Java中实现一个简单的日程提醒工具,核心是结合时间调度与用户提示功能。可以通过java.time处理日期时间,使用TimerScheduledExecutorService进行任务调度,并通过控制台输出或图形界面弹窗提醒用户。

1. 定义日程任务类

每个提醒任务应包含标题、描述和提醒时间。使用LocalDateTime表示具体时间点。

class ScheduleTask {
    private String title;
    private String description;
    private LocalDateTime remind

Time; public ScheduleTask(String title, String description, LocalDateTime remindTime) { this.title = title; this.description = description; this.remindTime = remindTime; } public String getTitle() { return title; } public LocalDateTime getRemindTime() { return remindTime; } public String getDescription() { return description; } }

2. 使用ScheduledExecutorService调度提醒

将任务按计划时间延迟执行,利用ScheduledExecutorServiceschedule方法。

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

void scheduleReminder(ScheduleTask task) {
    long delay = Duration.between(LocalDateTime.now(), task.getRemindTime()).toMillis();
    
    if (delay < 0) {
        System.out.println("提醒时间已过:" + task.getTitle());
        return;
    }

    scheduler.schedule(() -> {
        System.out.println("⏰ 提醒:" + task.getTitle());
        System.out.println("详情:" + task.getDescription());
        System.out.println("时间:" + task.getRemindTime());
    }, delay, TimeUnit.MILLISECONDS);
}

3. 添加多个提醒示例

创建几个测试任务,设置不同时间点的提醒。

public static void main(String[] args) {
    ScheduleReminderTool tool = new ScheduleReminderTool();

    // 示例任务:5秒后提醒
    LocalDateTime soon = LocalDateTime.now().plusSeconds(5);
    tool.scheduleReminder(new ScheduleTask("开会", "团队周会", soon));

    // 示例任务:1分钟后提醒
    LocalDateTime later = LocalDateTime.now().plusMinutes(1);
    tool.scheduleReminder(new ScheduleTask("喝水", "记得补充水分", later));
}

程序运行后会在指定时间打印提醒信息。若需更友好提示,可加入声音播放或JavaFX弹窗。

基本上就这些,不复杂但容易忽略时间单位转换和时区问题。确保输入时间大于当前时间,避免负延迟导致任务不执行。关闭程序前调用scheduler.shutdown()释放资源。