简体   繁体   English

如何保持更新日期/日历对象?

[英]How to keep updating a date/calendar object?

I am making a small alarm clock application to brush up on Java. 我正在制作一个小型闹钟应用程序以使用Java。 The purpose of the app is to let the user set the clock time and alarm time, and then the alarm should "go off" when the system time is equal to the alarm time. 该应用程序的目的是让用户设置时钟时间和闹钟时间,然后当系统时间等于闹钟时间时,闹钟应“关闭”。

The clock class contains a Calendar and Date object. Clock类包含一个Calendar和Date对象。

The clock is referred to from a main method outside the class. 时钟是从类外部的main方法引用的。 In that main method, I have built a simple command line user interface, where the user can set the time of the clock and alarm. 在该主要方法中,我构建了一个简单的命令行用户界面,用户可以在其中设置时钟和闹钟时间。 By default, the clock is initialized to the current system time. 默认情况下,时钟初始化为当前系统时间。

However, here is where the problem is for both the automatically initialized and the user defined clock objects - they aren't "ticking" or updating. 但是,这是自动初始化的时钟对象和用户定义的时钟对象都存在的问题-它们不是“滴答”或更新。

Clock regularClock = new Clock(); //Defaults clock (using a Date) to the system time

while (userInput != "Quit")
{
   switch(userInput)
   {
      ...Other choices here...
      case "Set Time":  System.out.print("Enter hour: ");
                    hours = kb.nextInt();
                System.out.print("\nEnter minutes: ");
                minutes = kb.nextInt();
                ACR.regularClock.setTime(hours, minutes);
                System.out.println("Clock has been set");

       case "Set Alarm": System.out.print("Enter hour: ");
            hours = kb.nextInt();
            System.out.print("\nEnter minutes: ");
            minutes = kb.nextInt();
            ACR.alarmClock.setTime(hours, minutes);
            ACR.alarmClock.setAlarmOn(true);
            System.out.println("Alarm has been set.");
            break;
      ...Other choices here...

  userInput = keyboard.next();
   }

As you will see, there are no loops or anything to refresh or keep the regularClock ticking. 如您所见,没有循环或任何可刷新或保持regularClock滴答的东西。 For some reason, when I started I thought Date and Calendar objects just kept running once created - sort of like a stopwatch. 由于某种原因,当我开始时,我以为Date和Calendar对象一旦创建就可以继续运行-就像秒表一样。

So now I'm wondering what the best way to update them would be, in this while loop. 所以现在我想知道在while循环中更新它们的最佳方法是什么。 If only the default system time clock was allowed, it would be easy - I could just create a new Date object at the beginning of the while loop each time. 如果只允许使用默认的系统时钟,那将很容易-我可以每次在while循环的开头创建一个新的Date对象。 However, that would override the user created clock time if they chose that. 但是,如果他们选择了该时间,它将覆盖用户创建的时钟时间。

Also, if the user weren't to enter any input - and instead just let the app sit there - where he/she would enter input - shouldn't it still be refreshing the times and checking if the regularClock = alarmClock time? 另外,如果用户不输入任何输入-而是让应用坐在那里-他/她将在其中输入输入-它是否还应该刷新时间并检查是否RegularClock = alarmClock时间? How can I do this? 我怎样才能做到这一点?

I realize I'm sort of rambling now, so I'll leave it at that. 我意识到我现在正在四处闲逛,所以我将其保留。 I've been working at this but can't figure out the best solution. 我一直在努力,但是找不到最佳解决方案。 If you have any questions, please let me know! 如有任何疑问,请告诉我!

Short summary questions: 简短摘要问题:

  1. How do I keep a the time in a Date or Calendar object ticking, even when it has been modified? 即使修改了日期或日历对象,如何在其上打勾呢?

  2. How can I continuously update these objects, while waiting for user input? 如何在等待用户输入的同时不断更新这些对象?

There are easier ways, but that's not the question ;) 有更简单的方法,但这不是问题;)

Basically, you need to establish some kind of "tick" thread that can update/modify the clock in the background... 基本上,您需要建立某种“滴答”线程,可以在后台更新/修改时钟。

You can write your own Thread / Runnable to perform these tasks, but they are inherently inaccurate... 您可以编写自己的Thread / Runnable来执行这些任务,但是它们本质上是不准确的...

Something like... 就像是...

Thread thread = new Thread(new Ticker());
thread.setDaemon(true); // Otherwise the JVM won't stop when you want it t
thread.start();

//...

public class Ticker implements Runnable {
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException exp) {
            }
            // Update static reference to the clock...
        }
    }
}

Beware though 不过要当心

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. 根据系统计时器和调度程序的精度和准确性,使当前正在执行的线程进入休眠状态(暂时停止执行)达指定的毫秒数。 The thread does not lose ownership of any monitors. 该线程不会失去任何监视器的所有权。

Another way would be use the java.util.Timer 另一种方法是使用java.util.Timer

Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new Ticker(), 1000, 1000);

//...

public class Ticker extends TimerTask {
    public void run() {
        // Update static reference to the clock...
    }
}

Again, beware... 再次提防...

Subsequent executions take place at approximately regular intervals 随后的执行大约每隔一定间隔执行一次

Date and Calendar objects do not 'run' - they represent specific points in time. 日期和日历对象不会“运行”-它们代表特定的时间点。 I believe that what you are looking for is the Timer class. 我相信您正在寻找的是Timer类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM