简体   繁体   English

如何在一定时间内运行TimerTask

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

I have a method that has to take a picture of the screen every 0.5 seconds and saves the image in a place on the HD. 我有一种方法,每0.5秒拍一次屏幕,并将图像保存在HD的某个位置。 But I need him to run between 11:55 am and 4:55 pm to 5:00 pm 但我需要他在上午11:55至下午4:55至下午5:00之间运行

I just got to start the Task and I could not stop it. 我刚刚开始任务,我无法阻止它。

My doubt is: 我的疑问是:

How could I schedule, for the thread to run only within a certain period of time. 我如何安排,让线程只在一段时间内运行。

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任务计划程序按计划运行程序,或者如果您希望程序控制它,您可以有一个连续运行的循环,休眠30秒然后检查时间,并运行代码,如果它是期望的时间。

For this task I would use two ExecutorServices. 对于此任务,我将使用两个ExecutorServices。

One checks every minute if it is the right time frame and the second executes your program code every 0.5s. 如果时间正确,则每分钟检查一次,第二次每隔0.5秒执行一次程序代码。

http://tutorials.jenkov.com/java-util-concurrent/executorservice.html 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);
}

To implement the inTimePeriod() function see this question: Check if a given time lies between two times regardless of date 要实现inTimePeriod()函数,请参阅以下问题: 检查给定时间是否介于两次之间而不管日期

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

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