Scheduling a task in Java for a specified date

2019-08-11 11:13发布

问题:

i am looking forward to learn java. I made this program , so that when the current date matches the specified date, it will execute some code, in this case, it will exit the while loop. I'd like to know if there any other ways, but for now i will stick with this string comparison.

For somewhat reasons the If loop isn't working properly, i monitor the current date with System.out.println(date) but when it reaches the desired date (by format HH:MM:SS) to do the action,the strings aren't equal and the while loop continues, is there anything i miss?

EDIT: Platform = windows 7

public class Main {

static String DesiredDate;
static String date;
static boolean Programisrunning;

public static void main(String[] args) {

DesiredDate = "17:24:10";

 while(Programisrunning = true) {

     date = CurrentDate.GetDate();
     System.out.println(date);

     if(date.equals(DesiredDate)) {
         Programisrunning = false;
        }

    }

 System.out.println("Program succesfully terminated");

   }

}

//another class

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentDate {

public static String GetDate(){
       DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

       Date date = new Date();
       return dateFormat.format(date);
     }

   }

回答1:

To schedule a task, use a ScheduledExecutorService:

Date desiredDate = // ...
Date now = new Date();
long delay = desiredDate.getTime() - now.getTime();

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.schedule(new Runnable(){
    @Override
    public void run() {
        Programisrunning = false;
        // + do other things?
    }
}, delay, TimeUnit.MILLISECONDS); // run in "delay" millis


回答2:

Executors

While loop solution is bad because CPU is busy. Use executors, specifically ScheduledExecutorService.

long delay = desiredDate.getTime() - System.currentTimeMillis();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);


回答3:

For calculations you should convert the text based date "hh:mm" in a long value, which represents the number of millis seconds sicne 1.1.1970 (UTC).

This value, e.g is delivered by System.currentTimeMillis();

The SimpleDateFormat will deliver the Date from a given formated human readable time (yyyy hh:mm:ss), too, the long value, can be get with date.getTime();

With that background use the class ScheduledExecutorService to run a task at given time.



回答4:

You can just use the Timer class to do time:

/**
 * Runs a timer for the specified length.
 * @param milliseconds the amount of milliseconds to run for.
 * @param seconds the amount of seconds to run for.
 * @param minutes the amount of minutes to run for.
 * @param hours the amount of hours to run for.
 */
public void timerallfeatures(int milliseconds, int seconds, int minutes, int hours){
    int Timeinterval = (hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000) + milliseconds;
    Timer timer = new Timer();
    timer.schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Your timer is up!");
            // Do stuff here
        }
    }, Timeinterval);
}

Or a repeating timer:

/**
 * Runs a timer for the specified length.
 * Timer repeats.
 * @param milliseconds the amount of milliseconds to run for.
 * @param seconds the amount of seconds to run for.
 * @param minutes the amount of minutes to run for.
 * @param hours the amount of hours to run for.
 */
public void timerallfeaturesrepeating(int milliseconds, int seconds, int minutes, int hours){
    int Timeinterval = hours * minutes * seconds * milliseconds;
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Your timer is up!");
        }
    }, Timeinterval, Timeinterval);
}

the Timer class also has a schedule(TimerTask, Date) method to execute a Date instead of a length of time (in milliseconds)

You can also look at a library I have written to help with java io and timer functions called "Shared Packages" which has a range of timers: https://github.com/JD9999/Shared-Packages/tree/master/Timers