我目前正在尝试使用 java 在我进入程序的特定时间打开我的默认网络浏览器以观看 YouTube 视频(以发出某种警报)
这是我的代码:
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.IOException;
public class YtAlarm
{
int hr;
int min;
public YtAlarm(int hours, int minutes) //constructor
{
hr = hours;
min = minutes;
}
public static void main (String [] args) throws URISyntaxException, IOException //main method
{
String url = "https://www.youtube.com"; //link to open once alarm goes off
YtAlarm ytalarm = new YtAlarm(15, 20); //sets alarm to go off at 3:20 PM
long alarm1 = ytalarm.convertTimeToMilli(); //converts alarm time to ms
do //checks what time it is on each itteration and once alarm1== curent time, opens yt video
{
if (System.currentTimeMillis() == alarm1)
{
if (Desktop.isDesktopSupported())
{
Desktop.getDesktop().browse(new URI(url));
}
}
}
while (System.currentTimeMillis()!= time);
}
public long convertTimeToMilli() //method to convert alarm time from hours and minutes to ms
{
long milli = (60000*min) + (3600000*hr);
return milli;
}
}
此代码编译时没有错误,但无法正常运行。当当前时间与我在构造函数中输入的时间匹配时,它不会打开我输入的链接。有谁知道如何更改我的代码,使其按照我想要的方式运行?
最佳答案
首先将您的alarm1值与System.currentTimeMillis()值进行比较,您就会知道原因。实际上 System.currentTimeMillis() 给你从 1970 年 1 月 1 日到现在的总毫秒数,而你的是从午夜到那个时间(15:20)的总毫秒数。
您可以使用
LocalDateTime now = LocalDateTime.now();
int hour=now.getHour();
int 分钟=now.getMinute();
之后比较小时与 hr 以及分钟与 min。
关于java - 如何用java设置闹钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144939/