I'm making a cookie clicker sort of game and I want a thing where every second a certain number let's say 5 is added to another number. So every second the integer variable is going up by 5. How would I create a sort of time measuring method where it measures time so I can add a number to another number.
public class timeTesting {
// I've put this method here for someone to create
// a timer thing
void timer()
{
}
public static void main(String[] args) {
// Original number
int number = 1;
// Number I want added on to the original number every 5 seconds
int addedNumber = 5;
}
}
You can use Timer to schedule a TimerTask who has the desired code inside the run() method. Check the code below (run() will be called once after 5000 milliseconds) :
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
number += addedNumber;
}
}, 5000);
Also you can use scheduleAtFixedRate(TimerTask task, long delay, long period) for repetitive tasks (here run will be called immediately, and every 5000 milliseconds):
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
number += addedNumber;
}
}, 0, 5000);
If you're targeting the android platform you could use CountDownTimer, which allows you to execute some code every certain amount of time for a certain duration. But be aware that android doesn't work with the main method like J2SE does.
Anyway, if you're looking foward to program an android game, i'd highly recommend you to start here: Android Development
I'd like to suggest start studying RxJava. Reactive programming is very powerful for games development: https://www.youtube.com/watch?v=WKore-AkisY
With RxJava, your problem can be solved with Observable interval() method:
https://github.com/Netflix/RxJava/wiki/Creating-Observables#interval
Ivan
You should consider using a Timer which will fire an event when a certain time interval has passed. It can repeat the event every so often, too.
Not very elegant, but working code:
public class MyTimer {
private volatile int number; //must be volatile as we're working on multiple threads.
private final int numberToAdd;
private final long timerTimeInMillis;
public MyTimer() {
number = 1;
numberToAdd = 5;
timerTimeInMillis = 5000;
}
public void runTimer() {
new Thread() { //declaring a new anonymous Thread class
public void run() { //that has to override run method.
while (true) //run the program in an infinite loop
{
number += numberToAdd; //add a number
System.out.println("Added number. Now the number is: " + number);
try {
Thread.sleep(timerTimeInMillis); //and then sleep for a given time.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); //and here we're starting this declared thread
}
public static void main(String[] args)
{
new MyTimer().runTimer();
try {
Thread.sleep(100000); //this application will work for 100sec.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Using java.util.Timer would be more elegant, but in here you may get aquainted with anonymous classes.
Related
I have a requirement to run a Java program with the following functionalities.
There should be a function (Say fetchTimeLimits()) that fetches two values of time. Time limit A and Time limit B. Note that both these time limits are future time values of the type Instant(). The fetching of these values should happen every 5 seconds.
There should be a function (Say functionA()) that utilizes time limit A. function A runs a while loop which sends out a calculated value until Time limit A is over. There is a sleep time of 1 second within the while loop.
There should be a function (Say functionB()) that utilizes time limit B. function B runs a while loop which sends out a calculated value until Time limit B is over. There is a sleep time of 1 second within while loop.
To implement this, I added a timer task with an interval of 5 seconds. In the timer task, fetchTimeLimits() function is called. Also, Two separate threads are started for functionA() and functinB(), if they are null or not alive. This is because, functionA() and functionB() would take hours to complete execution.
However, the CPU usage and RAM usage of the Java program is considerably high and I can observe that the CPU usage graph shows spikes.
package com.test;
import java.time.Instant;
import java.util.Timer;
import java.util.TimerTask;
public class mainClass {
static Thread functionAThread = null;
static Thread functionBThread = null;
static volatile Instant timeA = null;
static volatile Instant timeB = null;
static Timer timer = new Timer();
public static void main(String[] args) {
startTimer();
}
private static void startTimer() {
timer.schedule(new TimerTask() {
#Override
public void run() {
fetchTimeLimits();
if (functionAThread == null || !functionAThread.isAlive()) {
functionAThread = new Thread(() -> {
functionA();
});
functionAThread.start();
}
if (functionBThread == null || !functionBThread.isAlive()) {
functionBThread = new Thread(() -> {
functionB();
});
functionBThread.start();
}
}
}, 0, 5000);
}
private static void fetchTimeLimits() {
// Fetch values of timeA and timeB
}
private static void functionA() {
while (timeA != null && timeA.compareTo(Instant.now()) > 0) {
try {
Thread.sleep(1000);
// Calculate a value and send it.
} catch (InterruptedException e) {
}
}
}
private static void functionB() {
while (timeB != null && timeB.compareTo(Instant.now()) > 0) {
try {
Thread.sleep(1000);
// Calculate a value and send it.
} catch (InterruptedException e) {
}
}
}
}
Is there a better way to handle the requirement?
We have a complex calculation that takes a variable time. With some input values thousand steps can be done in one second - with other input values a step takes several seconds.
That's completely correct, so we just want to inform the user about the progress. The problem is that in the former case updating the GUI takes longer than the actual calculation, so after it is done there are still about 10 seconds of GUI update events in the queue (which in that case triples the execution time of the entire calculation).
I think that's a general problem, so I broke it down to a somewhat framework agnostic example:
public class QueueTest {
static final int STEPS = 30;
public static void main(String[] args) {
final Gui gui = // ...
final Display display = Display.getDefault();
final Thread thread = new Thread(() -> {
for (int i = 0; i < STEPS; i++) {
final int step = i; // calculate something etc.
gui.updateLater(display, step);
}
System.out.println("Finished calculation.");
});
thread.start();
while (true) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
interface Gui {
default void updateLater(Display display, int step) {
display.asyncExec(() -> update(step));
}
default void update(int step) {
System.out.println("Update " + (step + 1) + " / " + STEPS);
if (step == STEPS - 1) {
System.out.println("Finished GUI.");
}
}
}
}
(The additional Thread only "calculates" steps and sends it to the GUI to show the progress.)
So let's consider some implementations of Gui:
static class NoGui implements Gui {
#Override
public void update(int step) {
if (step == STEPS - 1) {
System.out.println("Finished GUI.");
}
}
}
This example prints only when the GUI is finished. The result is these two lines, printed at almost the same time:
Finished calculation.
Finished GUI.
That's perfectly reasonable. The GUI events are quick to be finished. Now let's make them slow:
static class SlowGui implements Gui {
#Override
public void update(int step) {
try {
Thread.sleep(100);
Gui.super.update(step);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
This prints something like the following, with the finishing of calculation and the GUI three seconds apart:
Finished calculation.
Update 1 / 30
Update 2 / 30
Update 3 / 30
...
Update 30 / 30
Finished GUI.
That's what I'm seeing in our application. The calculation finishes, but the GUI is too slow and has to execute its event queue after the calculation is already done.
I want to optimize this behavior and came up with something like this:
static class IgnorantGui extends SlowGui {
private boolean inProgress;
private Integer nextStep;
#Override
public void updateLater(Display display, int step) {
if (this.inProgress) {
this.nextStep = Integer.valueOf(step);
} else {
this.inProgress = true;
super.updateLater(display, step);
}
}
#Override
public void update(int step) {
try {
Integer currentStep = Integer.valueOf(step);
do {
super.update(currentStep.intValue());
currentStep = this.nextStep;
this.nextStep = null;
} while (currentStep != null);
} finally {
this.inProgress = false;
}
}
}
The output is the following four lines:
Finished calculation.
Update 1 / 30
Update 30 / 30
Finished GUI.
This implementation just ignores the events in between and so is a lot quicker. This is a valid solution to my problem.
I think this entire use case might be common, and maybe there is a more elegant solution. Or even some standard Java API to handle it. (Maybe some SWT / Eclipse Framework API, since that's what we're using.)
So... how to handle a GUI that takes longer to update than the calculation and so slows the application down?
One way that I use is to poll the background thread using a timer runnable in the UI thread. Use Display.timerExec for this:
display.timerExec(100, new Runnable() {
#Override
public void run() {
// TODO update UI from background thread details
// Run again
display.timerExec(100, this);
}
});
The background thread doesn't do any asyncExec calls it just maintains data that the UI thread can access.
don't know if I get it right but it seems that you are continuously updating the GUI. Try to add something like a counter that determines when the gui should be updated. Or if it isnt needed to see all steps try something like
static class SlowGui implements Gui {
#Override
public void update(int step) {
try {
if(step%5==0){
Gui.super.update(step);
}
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
this should update every 5 steps.
And why is there a sleep in the update method?
Hope I could help you.
When I start the app "specific function" needs to be executed.
After 10 seconds "specific function" needs to be triggered again.
After this second operation "specific function" should not triggered again.
There are two way to handle your problem.
If there is any condition you want to check and accordingly do the work after every 10 seconds You should Use a Handler.
If there is no condition on anything and you just want to run the code after every 10 Seconds. Then TimerTask is also one way. I have actually worked with TimerTask class. So i say it is quite easy.
Creating your class and implementing the methods.
class myTaskTimer extends TimerTask{
#Override
public void run() {
Log.e("TAG", "run: "+"timer x");
}
}
and now in your code Create a new Timer Object and initialize it.
Timer t = new Timer();
Now you can schedule your task in it after a specified interval like below:
t.scheduleAtFixedRate(new myTaskTimer(),10000,10000);
The function is explained below:
void scheduleAtFixedRate (TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution,
beginning after the specified delay. Subsequent executions take place
at approximately regular intervals, separated by the specified period.
and now for handler , below is the code and it can check for any condition. Code taken from here for your help.
private int mInterval = 10000; // 10 seconds as you need
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
// your code here
mHandler = new Handler();
startRepeatingTask();
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
updateStatus(); //this function can change value of mInterval.
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
I hope it helps.
Use android.os.Handler as per #pskink comment.
private void callSomeMethodTwice(){
context.myMethod(); //calling 1st time
new Handler().postDelayed(new Runnable(){
#Override
public void run(){
context.myMethod(); //calling 2nd time after 10 sec
}
},10000};
}
The version of Java is 8u60.
I want to write a void method which could pause the program for 1 seconds but there are always exceptions.
public void OnePause(){
Timer timerOne = new Timer();
timerOne.schedule(timerOneTask(), (long)1000);}
private TimerTask timerOneTask() {
return null;
}
}
I do not want to use Thread.Sleep(); because it pauses the sum of all time when called multiple times instead of pause separately.
Thanks a lot.
Right now your code is broken. Besides trying to send null into Timer.schedule(...), your statement timerOne.schedule(timerOneTask(), (long)1000);} is going to call timerOneTask() every 1000 milliseconds, but that does not pause the program. You must sleep the thread:
private TimerTask timerOneTask(int sleepTime) {
return new DoNothingTimerTask extends TimerTask {
public void run() {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// awoken prematurely, handle this
}
}
}
Unless you need to schedule the "pauses" on some interval, there's no use in introducing the Timer API into the mix; if not, you can get simply use what's in that try...finally block.
I study a thread and trying make a timer using thread. To the main thread wrote a time
public class A {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, write the time in ms");
long time = Long.parseLong(reader.readLine());
B thread = new B();
int timer = 0;
try {
thread.start();
Thread.sleep(time);
timer=thread.stop();
}
catch(InterruptedException e) {
System.out.println("Oh....");
}
System.out.println("Result is "+timer);
}
}
and every millisecond program write a name of specific millisecond in child thread.
public class B implements Runnable {
private volatile boolean running=true;
private int timer=0;
Thread thread;
public B() {
thread = new Thread(this);
}
public void run() {
while (running) {
System.out.println(timer);
timer++;
try {
Thread.sleep(1);
}
catch(InterruptedException e) {
System.out.println("B");
}
}
}
public int stop() {
running = false;
return timer;
}
public void start() {
thread.start();
}
}
But when try with parameter 50 get the result 37. I want understand how to synchronize it in the time. Can you explain me how to do it correct?
When time is over just set the variable running to false,it will end the while loop and the child thread will also be finished.
So after below line, try to set running variable to false.(provide some setter method or may be in constructor argument)
Thread.sleep(time);
You are forgetting that all the statements other than Thread.sleep(1) also take time to execute. Most notably the System.out.println(timer): this is an I/O operation and whenever such an operation takes place, it usually sucks time (printing to screen makes the program wait for this blocking I/O operation to complete).
But I like to demonstrate a more subtle assumption: you also assume that when thread.start() returns, B.run() is executing. This is not the case, as is demonstrated in the following little program:
import java.util.concurrent.TimeUnit;
public class ThreadTimer implements Runnable {
public static void main(String[] args) {
ThreadTimer tt = new ThreadTimer();
long afterStart = 0L;
new Thread(tt).start();
afterStart = System.nanoTime();
println("After start: " + afterStart);
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
long deltaStart = tt.realStart - afterStart;
println("Delta start: " + deltaStart);
long deltaStartMs = TimeUnit.NANOSECONDS.toMillis(deltaStart);
println("Delta start ms.: " + deltaStartMs);
}
public long realStart;
#Override
public void run() {
realStart = System.nanoTime();
println("Real start : " + realStart);
}
private static void println(String msg) {
System.out.println(msg);
}
}
On my system this shows:
After start: 40062314666459
Real start : 40062314706827
Delta start: 40368
Delta start ms.: 0
Which means a little bit of time was lost. I'm sure that if you measure how long it takes to perform System.out.println(timer), you will see more little bits of time lost. All these little bits eventually add up to quite a chunk of time not accounted for.
On a final note: System.nanoTime() and System.currentTimeMillis() also take time to execute (it takes time to measure the time).