【发布时间】:2021-10-15 07:56:49
【问题描述】:
我有一小部分程序有一个计时器,它每 15 分钟通过命令行 (fswebcam) 使用 USB 网络摄像头拍照。
代码是这样的:
public static final String HOME_DIR = System.getProperty("user.home") + "/";
public static final String PGP_DIR = HOME_DIR + "PGP/";
public static final String COLLECTION_DATA_DIR = PGP_DIR + "collectionData/";
public static final String SENSOR_CALIBRATION_DATA = PGP_DIR + "sensorCalibration/";
public static final String PICTURE_DIR = PGP_DIR + "pictures/";
public static final String ALARM_DIR = PGP_DIR + "alarms/";
private class PictureTakerTask extends TimerTask{
Timer t;
public void start(){
if(t != null){
t.cancel();
t.purge();
t = null;
this.cancel();
}
t = new Timer(true);
t.scheduleAtFixedRate(this, 0, 1000 * 60 * 15); //takes a picture every 15 minutes
}
public void stop(){
if(running) return;
if(t != null){
t.cancel();
t.purge();
t = null;
}
this.cancel();
}
@Override
public void run() {
String filename = getPictureFilename();
if(filename == null) return;
Process p;
try {
CommIO.printLog("Taking a picture");
String file;
light.setGreenPWM(80);
p = Runtime.getRuntime().exec("fswebcam -r 1920x1080 --no-banner -S 1 " + filename);
p.waitFor();
System.out.println ("picture taken with exit value: " + p.exitValue());
p.destroy();
light.setGreenPWM(0);
} catch (Exception e) {
e.printStackTrace();
light.setGreenPWM(0);
}
}
private String getPictureFilename(){
//make folder if it doesn't exist already
SimpleDateFormat justDate = new SimpleDateFormat("MM-dd-yy");
String date = justDate.format(new Date());
String s = PICTURE_DIR + date + "/";
File picDir = new File(s);
if(!picDir.exists()){
if(picDir.mkdir()){
Alert alert = new Alert(AlertType.ERROR, "Couldn't make picture directory: " + s, ButtonType.OK);
}
}
//find an unused filename
String picFileName = s + "plant_01.jpg";
File tempFile = new File(picFileName);
int i = 1;
while (tempFile.exists()) { //finds the next nonexistent name for data spreadsheet
String num = i < 10 ? "0" + i : "" + i;
picFileName = s + "plant_" + num + ".jpg";
i++;
tempFile = new File(picFileName);
if(i > 10000) break;
}
return picFileName;
}
}
线程启动并正常工作,直到午夜。第二天就不能拍照了。我无法弄清楚为什么它会停止。如果我停止并重新启动任务,它将再次正常工作。如果我什至通过程序外的终端拍照,它会再次正常工作。它只会在第二天停止拍照。它甚至创建了第二天的文件夹,只是没有图片。没有错误消息(我可以找到)。
有人对此有任何想法或经验吗?在你说之前,不,我不能使用运动或 Cron,因为我需要与 run() 函数中的“light”对象同步。
【问题讨论】:
-
…或 Cron,因为我需要与 run() 函数中的“轻”对象同步。为什么,碰巧,cron 会有问题?您可以在 cron 脚本中设置灯光。另一个问题:你总是得到一个零的退出代码吗?
-
PICTURE_DIR到底是什么? -
java.util.Date或java.sql.Date? -
util.Date。同样g00se,所讨论的“灯”实际上与串行端口相关联,并且在同一程序中的单独计时器(实际上是多个计时器)中频繁地(大约每秒一次)进行通信。我不想通过单独的程序来处理额外的资源/同步冲突问题,单独的计时器已经够头疼了。
-
@BasilBourque 编辑问题以包含目录。简化为“pihome”/PGP/pictures
标签: java raspberry-pi4