如何在某个时间段内创建一个 TimerTask 运行 并

How can I make a TimerTask run in a certain period and to

我有一个方法,必须每 0.5 秒拍摄一次屏幕照片,并将图像保存在 HD 上的某个位置。但是我需要他在11:55a.m之间运行。和 4:55 p.m。至 5:00 p.m.

我刚开始任务,但无法停止。

我的疑问是:

我怎么安排,让线程只在某个时间段内运行。

public class Main {

private Toolkit a = Toolkit.getDefaultToolkit();
private Dimension screenSize = a.getScreenSize();
private Rectangle screenLimit = new Rectangle(screenSize);
private Robot robot;

private File file;

BufferedImage img;


private final static int TWO_AM = 11;
private final static int ZERO_MINUTES = 28;



private static Date getTomorrowMorning1145AM(){

    Date date2am = new java.util.Date(); 
       date2am.setHours(TWO_AM); 
       date2am.setMinutes(ZERO_MINUTES); 

       return date2am;
  }



public Main() {

    String path = "c:\print\"+System.getProperty("user.name")+"\";

    try {
        robot = new Robot();
        file = new File(path);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

    if(!file.exists()){
        file.mkdirs();
    }

    TimerTask tt = new TimerTask() {

        @Override
        public void run() {

            try {
                tirarPrint(path+"print_" + new Date().getTime() + ".jpg");
            } catch (IOException | AWTException e) {
                e.printStackTrace();
            }

        }
    };

    Timer t = new Timer();

    t.schedule(tt, 0, 500);

}

private void tirarPrint(String caminho) throws AWTException, IOException {

    img = robot.createScreenCapture(screenLimit);
    ImageIO.write(img, "jpg", new File(caminho));

 }

public static void main(String[] args) {
    new Main(); 
  }
}

您可以使用 windows 任务调度程序按计划 运行 程序,或者如果您希望程序控制它,您可以有一个连续 运行s 的循环, 休眠 30 秒,然后检查时间,如果是所需时间,运行输入代码。

对于这个任务,我将使用两个 ExecutorServices。

一个每分钟检查一次时间范围是否正确,第二个每 0.5 秒执行一次您的程序代码。

http://tutorials.jenkov.com/java-util-concurrent/executorservice.html

public static ScheduledExecutorService timerFrameExecutor = Executors.newSingleThreadScheduledExecutor();
public static ScheduledExecutorService shortTimeExecutor = Executors.newSingleThreadScheduledExecutor();

public static void main(String[] args) {
    Runnable timerFrameRunnable = new Runnable() {

        @Override
        public void run() {
            if (inTimePeriond() == false) {
                shortTimeExecutor.shutdown();
            } else {
                if (shortTimeExecutor.isShutdown()) {
                    Runnable shortTimeRunnable = new Runnable() {

                        @Override
                        public void run() {
                            // do your stuff
                        }
                    };
                    shortTimeExecutor.scheduleAtFixedRate(shortTimeRunnable, 0, 500, TimeUnit.MILLISECONDS);
                }
            }
        }
    };
    timerFrameExecutor.scheduleAtFixedRate(timerFrameRunnable, 0, 1, TimeUnit.MINUTES);
}

要实现inTimePeriod()功能请看这个问题: Check if a given time lies between two times regardless of date