我目前正在研究Java应用程序,它每秒都会检查计算机的温度。为了时间的关系,我创建了一个与Timer
一起使用的Quartz
类,并且为了检查温度,我创建了一个名为SysKeeper
的类。我的问题是,我想要的是,SysKeeper
会在Timer
被触发时被通知,但我的Observer
无效,因为Syskeeper
未被添加为Observer
。
在这里,您可以看到我的Syskeeper
课程:
public class SysKeeper implements Observer {
private double temp;
public void start() {
Log.info("SysKeeper starting");
Main.timer.addObserver(this);
}
private void checkTemp() {
String buffer = CmdExecutor.execute("sudo vcgencmd measure_temp");
String[] splitBuffer = buffer.split("=");
String[] splitBuffer1 = splitBuffer[1].split("\'");
temp = Double.parseDouble(splitBuffer1[0]);
if (temp > 70.0) {
//Main.not.sendMessage("Reached crit Temp: " + temp);
}
Log.info(temp + "");
}
public void kill() {
}
@Override
public void update(Observable o, Object arg) {
System.out.println("HI");
this.checkTemp();
}
}
这是我的Timer
课程:
public class Timer extends Observable implements Job {
public void start() {
try {
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("timer", "timer")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
.build();
JobDetail job = JobBuilder.newJob(Timer.class)
.withIdentity("timer", "timer").build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException ex) {
Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
this.setChanged();
this.notifyObservers();
System.out.println("" + countObservers());//always 0
}
public void kill() {
}
}
这也是我的Main
课程:
public class Main {
public static final String spliterNetwork = ";";
public static final String spliterParameter = "#";
public static Timer timer;
public static Server ser;
public static SysKeeper kep;
public static GPIO gpio;
public static Log log;
public static void main(String[] args) throws UnknownHostException {
Main.init(args);
Main.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
Main.stop();
}
}));
}
public static void init(String[] args) {
timer = new Timer();
log = new Log();
ser = new Server();
kep = new SysKeeper();
gpio = new GPIO();
}
public static void start() throws UnknownHostException {
Log.info("Welcome to iServer @ " + InetAddress.getLocalHost());
timer.start();
log.start();
ser.start();
kep.start();
gpio.start();
}
public static void stop() {
Log.info("Programm shuts down");
timer.kill();
log.kill();
ser.kill();
kep.kill();
gpio.kill();
timer = null;
log = null;
ser = null;
kep = null;
gpio = null;
Log.info("Good bye");
}
}
答案 0 :(得分:1)
我对Quartz不熟悉,但似乎你有两个不同的Timer
实例:
Timer
中存储的第一个Main.timer
,在timer = new Timer()
中创建,并在Main.timer.addObserver(this);
(SysKeeper
中)添加了观察者。永远不会执行此实例,也就是说,它永远不会调用execute()
方法。Timer
中的第一个Timer
创建的第二个JobDetail job = JobBuilder.newJob(Timer.class)...
此Timer
是正在执行的scheduler.scheduleJob(job, trigger);
(Observer
)但它没有任何{{1}}附加。