java中怎么在计时器的time类中加提醒功能(类似闹钟)设计在增加提醒功能
下面是一个简单的实现:
1、先用LocalDateTime.now()方法获取现在的时间
2、然后用Scanner获取闹钟设置在几小时几分几秒后
3、使用LocalDateTime类的plus系列方法计算闹钟时间
4、在一个while循环汇总使用Duration的between()方法不断判断现在和闹钟时间相差的毫秒数,如果相差等于0,则退出循环
5、闹钟提醒使用第三方jar包JLayer类调用本地音乐实现闹钟提醒。
参考链接:
java.time包中常用的三个类的总结及使用[java]_java码农进化ing的博客-CSDN博客_java time包
Java 8中通过增加小时、分钟、秒数来计算将来时间_多汁多味的博客-CSDN博客_java 计算多少分钟后的时间
LocalDate/LocalDateTime时间类型比较时间的先后是否相等;java计算时间差;java8时间加减;DateUtils/DateFormatUtils工具类_好大的月亮的博客-CSDN博客_localdatetime比较时间
java实现播放音乐-JLayer - 青阳闲云 - 博客园
代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Scanner;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class Time {
public static void main(String[] args) throws FileNotFoundException, JavaLayerException {
// TODO Auto-generated method stub
//https://blog.csdn.net/m0_57001006/article/details/121551207
//获取现在时间
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("现在是:"+localDateTime.getHour()
+"点"+localDateTime.getMinute()
+"分"+localDateTime.getSecond()+"秒");
//从输入获取闹钟在几点几分几秒后
Scanner sc = new Scanner(System.in);
System.out.println("请输入几点几分几秒后提醒(用空格分隔):");
int hour = sc.nextInt();
int minute = sc.nextInt();
int second = sc.nextInt();
//计算闹钟时间
//https://blog.csdn.net/weixin_43652507/article/details/122623400
LocalDateTime endTime=localDateTime.plusHours(hour).plusMinutes(minute).plusSeconds(second);
System.out.println("闹钟时间是:"+endTime.getHour()
+"点"+endTime.getMinute()
+"分"+endTime.getSecond()+"秒");
//https://blog.csdn.net/weixin_43944305/article/details/106802976
//计算距离闹钟还有多久
LocalDateTime nowtime = LocalDateTime.now();
Duration duration = Duration.between(nowtime,endTime);
System.out.println("时间相差:"+duration.toMillis()/1000+"秒。");
//不断计算距离闹钟还有多久,直到时间相差为0
while(duration.toMillis()>0)
{
nowtime = LocalDateTime.now();
duration = Duration.between(nowtime,endTime);
//这里动态显示相差时间,可以自行调节
// System.out.println("闹钟倒计时,还有"+duration.toHours()+"小时"
// +duration.toMinutes()+"分钟"
// +duration.toMillis()/1000+"秒。");
}
System.out.println("时间到!");
//https://www.cnblogs.com/helf/archive/2021/08/27/15194821.html
//调用第三方的jar包JLayer类的方法播放本地音乐实现闹钟提醒
File file = new File("F:\\music.mp3"); //音乐文件地址
Player player = new Player(new FileInputStream(file));
player.play();//播放音乐
}
}