我正在创建一个通知用户约会时间的系统。我的问题:在用户添加约会时要监听的新约会并在右下角显示通知时创建Thread很好吗
我的代码
DateFormat inFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
DateFormat outFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Timer timer = new Timer();
private void appointmentNotification() throws ParseException {
//Convert 12hour time to 24hour
String dateValues = date + " " + time;
Date dateParse = inFormat.parse(dateValues);
timer.schedule(new TimerTask() {
@Override
public void run() {
Notifications noti = Notifications.create();
noti.text("Doctor "+doc+" has an Appointment with Patient "+patient);
noti.title("Appointment");
noti.hideAfter(Duration.seconds(10));
noti.position(Pos.BOTTOM_RIGHT);
Platform.runLater(new Runnable() {
@Override
public void run() {
noti.show();
}
});
}
}, outFormat.parse(outFormat.format(dateParse)));
}
我想如果用户添加了50个约会,就会有50个线程在运行
答案 0 :(得分:0)
所以我遵循Zephyr在评论中给出的逻辑,它对我有用。
我假设约会已添加到数据库了?如果是这样,只需创建一个后台线程即可定期轮询数据库。约会临近时,显示提醒。
代码:
private void displayAppointmentNotification() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
try {
ps = HospitalDB.getCon().prepareStatement("Select * From Notification");
rs = ps.executeQuery();
while (rs.next()) {
if (rs.getString("Reminder").contentEquals(dateFormat.format(new Date()))) {
Notifications noti = Notifications.create();
noti.text("Doctor " + rs.getString("Doctor") + " has an Appointment with Patient " + rs.getString("Patient"));
noti.title("Appointment");
noti.hideAfter(Duration.seconds(30));
noti.position(Pos.BOTTOM_RIGHT);
Platform.runLater(() -> {
noti.show();
});
//Change The Appointment Status to Done
ps = HospitalDB.getCon().prepareStatement("Update Appointment Set Status=? Where Patient=? and Doctor=?");
ps.setString(1, "Done");
ps.setString(2, rs.getString("Patient"));
ps.setString(3, rs.getString("Doctor"));
ps.executeUpdate();
populateTable();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.schedule(task, 0, 1 * 1000);
}
后台线程将始终查看数据库中的日期,如果与系统日期相同,它将显示通知