Why my Java alarm clock code doesn't work properly? - java

I want the code to trigger the JOptionPane.
Here is the code for the working clock:
new Thread() {
public void run() {
while (true) {
GregorianCalendar cal = new GregorianCalendar();
int hour = cal.get(GregorianCalendar.HOUR);
int min = cal.get(GregorianCalendar.MINUTE);
int sec = cal.get(GregorianCalendar.SECOND);
int AM_PM = cal.get(GregorianCalendar.AM_PM);
String day_night;
if (AM_PM == 1) {
day_night = "PM";
} else {
day_night = "AM";
}
String time = hour + ":" + min + ":" + sec + " " + day_night;
lblClock.setText(time);
}
}
}.start();
Here is code I wrote to trigger alarm, but no 'play sound' is coded yet, because I can't even get the JOptionPane to appear. Why? I want to get the values from spinners, than compare to real time until they meet and than trigger alarm and exit thread. How to fix it?
btnAlarm.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Thread() {
public void run() {
txtAlarmSet.setVisible(true);
boolean flag = false;
GregorianCalendar g = new GregorianCalendar();
int hour = Integer.parseInt(spinnerHour.getModel().getValue().toString());
int minute = Integer.parseInt(spinnerMinute.getModel().getValue().toString());
int second = Integer.parseInt(spinnerSecond.getModel().getValue().toString());
int AMorPM;
if (rdbtnAm.isSelected()) {
AMorPM = 0;
} else
AMorPM = 1;
while (flag == false) {
int realHour = g.get(GregorianCalendar.HOUR);
int realMinute = g.get(GregorianCalendar.MINUTE);
int realSecond = g.get(GregorianCalendar.SECOND);
int realAM_PM = g.get(GregorianCalendar.AM_PM);
if (hour == realHour && minute == realMinute && second == realSecond
&& AMorPM == realAM_PM) {
JOptionPane.showMessageDialog(null, "WORKS!"); // <- this doesn't appear!
flag = true;
}
}
txtAlarmSet.setVisible(false);
}
}.start();
}
});

In your checking loop, you need to reacquire the Calendar on every pass, otherwise, you'll just end up re-checking the same time value over and over. Move the line
GregorianCalendar g = new GregorianCalendar();
inside the loop.
Note: This is not a particularly good approach to this problem. What you're doing is called "busy waiting" and it's generally not good for much other than making the CPU get hot. A better approach would be to use an event-driven approach, but that's beyond the scope of this answer.

One major problem I notice is missing } after AMorPM = 1; making it impossible to work for AM.

Related

StatusUpdate Discord Bot

This is my code to update the Status:
String[] status = new String[] {"Version: 1.5.0", "https://discord.gg/arWEM2h", "Love Backxtar", "You want me!", "Type: ~help", "User Counter: %members"};
int next = 60;
public void onSecond() {
if(next%5 == 0) {
if(!hasStarted) {
hasStarted = true;
StatChannelCommand.onStartUp();
}
Random rand = new Random();
int i = rand.nextInt(status.length);
shardMan.getShards().forEach(jda -> {
String text = status[i].replaceAll("%members", "" + jda.getUsers().size());
jda.getPresence().setActivity(Activity.playing(text));
});
StatChannelCommand.checkStats();
if(next == 0) {
next = 60;
}
}
else {
next--;
}
}
But the String is running every second. I thought it was every 5 seconds. I did 60 sec % 5. What is wrong with this code?
When you enter the method onSecond() for the first time, the condition next%5 == 0 will be true. The variable next will not be updated, because this happens only in the else part. So, on next run of the method next will still be 60.

Running timer task at 0200 hrs everyday

I have a timer ejb that controls when the application runs that needs to be switched. I need to make it to run at 0200 hrs everyday
public void fireInTwentyFourHours() throws EJBException
TimerService theTimerService = mySessionCtx.getTimerService();
String aLabel = "24 Hours Interval";
//theTimerService.createTimer(new Date(),86400000, aLabel);
String stage = Stage.getStage();
List timerObjects = (List)theTimerService.getTimers();
if(null != timerObjects && timerObjects.size() > 0) {
for(int timerCount=0,size=timerObjects.size();timerCount<size;timerCount++) {
Timer timer = (Timer)timerObjects.get(timerCount);
timer.cancel();
}
}
if(stage.equalsIgnoreCase("P")){
theTimerService.createTimer(getRunTime(),86400000, aLabel);
} else {
theTimerService.createTimer(new Date(),86400000, aLabel);
}
}
private Date getRunTime() {
Calendar gc = new GregorianCalendar();
int year = gc.get(Calendar.YEAR);
int month = gc.get(Calendar.MONTH);
int date = gc.get(Calendar.DAY_OF_MONTH);
Calendar newDate = new GregorianCalendar(year,month,date,17,30,0);
return newDate.getTime();
}
I need to create a new method and make fireInTwentyFourHours to execute at 0200 hrs.
Is this the correct way to make it fire at 0200
public Date getTime(){
Calendar c = Calendar.getInstance();
Date d = c.getTime();
return d;
}
public void fireInTwentyFourHours() throws EJBException
TimerService theTimerService = mySessionCtx.getTimerService();
String aLabel = "24 Hours Interval";
//theTimerService.createTimer(new Date(),86400000, aLabel);
String stage = Stage.getStage();
List timerObjects = (List)theTimerService.getTimers();
if(null != timerObjects && timerObjects.size() > 0) {
for(int timerCount=0,size=timerObjects.size();timerCount<size;timerCount++) {
Timer timer = (Timer)timerObjects.get(timerCount);
timer.cancel();
}
}
if(stage.equalsIgnoreCase("P")){
theTimerService.createIntervalTimer(getTime(),86400000, aLabel);
} else {
theTimerService.createIntervalTimer(new Date(),86400000, aLabel);
}
}
the third parameter is timerConfig how to set that. will it make the code to run at 0200?

Java EventHander limitation (Time)

My code is about the game "Minecraft". I want a Array item list to drop random items, what works fine.
I am trying to set up a kind of scheduler for an EventHandler.
I want the EventHandler to be executed only 5 times a minute, or every 12 seconds or something.
If I work with a "Bukkit" "runTaskLater" function, the Code is executed with a delay, but after the delay it's running permanent.
Here you have my raw code without any Scheduler.
#EventHandler
public void on(PlayerMoveEvent e) {
Player p = e.getPlayer();
if(p.getLocation().getBlock().getType() == Material.STONE_PLATE) {
if(p.getLocation().subtract(0D, 1D, 0D).getBlock().getType() == Material.STAINED_CLAY) {
Block block = p.getLocation().getBlock();
Random ran = new Random();
int auswahl = ran.nextInt(2);
int zahl = ran.nextInt(main.Drops.size());
ItemStack itemstack = main.Drops.get(zahl);
block.getWorld().dropItemNaturally(p.getLocation(), itemstack);
}
}
}
and now this handler should be performed only every 12 seconds.
Do anyone have a solution for me?
Thanks a lot!
As i understand it, you want to have a cooldown. Just store the time of the last event in a variable and check if the current time is 12 seconds higher:
private long lastTime = System.currentTimeMillis();
#EventHandler
public void on(PlayerMoveEvent e) {
if (lastTime < System.currentTimeMillis() - 12000) {
Player p = e.getPlayer();
if(p.getLocation().getBlock().getType() == Material.STONE_PLATE) {
if(p.getLocation().subtract(0D, 1D, 0D).getBlock().getType() == Material.STAINED_CLAY) {
Block block = p.getLocation().getBlock();
Random ran = new Random();
int auswahl = ran.nextInt(2);
int zahl = ran.nextInt(main.Drops.size());
ItemStack itemstack = main.Drops.get(zahl);
block.getWorld().dropItemNaturally(p.getLocation(), itemstack);
}
}
lastTime = System.currentTimeMillis();
}
}
If it does not work, please comment :)

Strange crash with app

Recently my app crashes really strange, If I start the app it gives a white screen for a second or 10 and than it stops working.
logcat gives the following error but I don't understand it, can you guys help me ?
Error log too large, please look at it at pastebin:
Error log
EDIT------------------
I think this piece of code generates the error, it started after I added it:
Im only not sure what the error is, i don't understand the logcat output
{
Calendar cal = loadCurrentCalendar();
long currentMil = cal.getTimeInMillis();
int hourI = cal.HOUR_OF_DAY;
while (hourI <19)
{
currentMil = currentMil + ONE_HOUR;
hourI ++;
}
setSleepMil(currentMil + SLEEP_TIME); // TODO werkt dit ? + SLEEP_TIME stond hier achter currentMil
return getSleepMil();
}
public int hourPassedSleepCur(long sleepMil)
{
Calendar cal = loadCurrentCalendar();
long currentMil = cal.getTimeInMillis();
hoursPassed = 0;
while (sleepMil < currentMil)
{
hoursPassed ++;
setSleepMil(getSleepMil()+ ONE_HOUR);
}
return hoursPassed;
}
}
EDIT 2-------------------------------------------
Im accessing it with this piece of code witch runs in a thread that checks every few milisec
public void checkSleepyTime()
{
currentCalendar = timeHelper.loadCurrentCalendar();
int hour = currentCalendar.get(Calendar.HOUR_OF_DAY);
int daypart = currentCalendar.get(Calendar.AM_PM);
if (hour >= 20 && daypart == 1 || hour < 6 && daypart == 0)
{
foodButton.setText("ZZzz");
prefs.edit().remove("foodTime").commit();
buddy.setSleeping(true);
}
else
{
buddy.setFoodLevel(buddy.getFoodLevel() - timeHelper.hourPassedSleepCur(loadNextSleepyTime()));
// buttonTest.setText(timeHelper.hourPassedSleepCur(getNextSleepyTime()));
saveNextSleepyTime();
sleepTimeView.setText("sleepy at: " + String.valueOf(loadNextSleepyTime()));
foodButton.setText("Awake");
buddy.setSleeping(false);
}
}

TimerTask not executing?

Here is my timer class, This class is designed to constantly update a timer in a view. However, when I run the app the first toast message is displayed to the screen but the second one is never reached (the timerTask's "run" method is never executed). I know that this is probably something simple that I am doing wrong. If anyone could steer me in the right direcion that would be great.
public class MyTimer {
static Timer _timerTask = new Timer();
static int totalSeconds = 1, hour = 0, min = 0, sec = 0;
static String mTimeFormat = "%02d:%02d:%02d";
static String timeTakenString;
public static void start (){
Toast.makeText(GPSMain.context, "Message one", Toast.LENGTH_LONG).show();
TimerTask timer = new TimerTask() {
#Override
public void run() {
Toast.makeText(GPSMain.context, "Message two", Toast.LENGTH_LONG).show();
totalSeconds += 1;
sec += 1;
if(sec >= 60) {
sec = 0;
min += 1;
if (min >= 60) {
min = 0;
hour += 1;
}
}
timeTakenString = String.format(mTimeFormat, hour, min, sec);
postExecute.sendEmptyMessage(0); //update UI
}
private Handler postExecute = new Handler(){
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
GPSMain.timer.setText("Time Taken: "+timeTakenString);
}
};
};
_timerTask.scheduleAtFixedRate(timer,1000,1000);
}
}
code in another file calling this class:
MyTimer myTimer = new MyTimer();
....
myTimer.start();
PROJECT SPEC CHANGED!
My project leader changed the spec of the project so that it no longer needs to update the timer to the UI but rather display it as an end result. Accepting the first answer anyway as it solves the original problem. Will post the new code below.
New code calls:
System.currentTimeMillis();
at the beggining and end of the runcycle, which returns a long. The first value is then subtracted from the second value to calculate the amount of time taken to execute the runcycle. That value is then manipulated and put into a timer format that is displayed at the end as a string.
public static String getTimeTaken(long end, long start){
#SuppressWarnings("unused")
String formattedTime = "", hourHour = "", hourMin = ":", minSec = ":";
long timeTaken = (end-start)/1000, hour = 0, min = 0, sec = 0;
if (timeTaken>9 ){
hourHour = "0";
hourMin = ":0";
if (timeTaken>=60){
if (timeTaken>= 3200){
hour = timeTaken/3200;
timeTaken = timeTaken%3200;
if (hour>9){
hourHour = "";
}
}
min = timeTaken/60;
timeTaken = timeTaken%60;
if (min >9){
hourMin = ":";
}
}
sec = timeTaken;
if(sec%60<10){
minSec = ":0";
}
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
sec = timeTaken;
minSec = ":0";
hourMin = ":0";
hourHour = "0";
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
Using thread you cant update your UI for that you have to use runOnUiThread
youractivity.this.runOnUiThread(new Runnable(){public void run(){Toast.makeText(mContext, "Message", Toast.LENGTH_LONG).show();}});
(Very late...just answering in case someone reach this question... scheduling a task doesn't garantee it will run on the proper time... it may take longer, sometimes much longer...)

Categories