PDA

View Full Version : TimerExecuter - alternative to EventManager



Fenway`
June 24th, 2010, 06:22
ALL CREDITS TO TJ007RAZOR


This is easier to work with than EventManager.


You always release good shit tj.


"zOMG He's reinventing the wheel!!! LULZ n33b" - I don't care if I'm "reinventing the wheel", I do this because I would much rather use something that I made and improve upon it to help my understanding of the language than use something someone else made. If you don't want to use it, don't. If you do, please do.

Purpose: Add a TimerExecutor to handle the running of all Timers (+ add said Timer)
Difficulty: 2
Assumed Knowledge: The ability to read and copy and paste...then to actually use it you need a bit more knowledge of the Java language
Server Base: Originally Cheezescape u76, should work on all - no reason it shouldn't
Classes Modified: TimerExecutor.java, Timer.java


Procedure

Step 1: First we will add the TimerExecutor class
Create a new Java file and put this in it:


/**
* @name TimerExecutor.java
* @author tj007razor
*/

import java.util.LinkedList;
import java.util.List;
import java.util.Collections;

public class TimerExecutor implements Runnable
{
// instance of TimerExecutor
private static TimerExecutor executor;

/**
* @return instance of TimerExecutor
**/
public static TimerExecutor getSingleton()
{
if (executor == null)
executor = new TimerExecutor();
return executor;
}

// list of Timers
private List<Timer> timers;

/**
* Construct new instance of TimerExecutor
**/
public TimerExecutor()
{
timers = Collections.synchronizedList(new LinkedList<Timer>());
(new Thread(this)).start(); // one thread to run all Timers (not one for each)
}

/**
* Add a Timer to the list of timers
* @param Timer to add to the list
**/
public void add(Timer timer)
{
synchronized(timers)
{ timers.add(timer); }
}

/**
* Handle all timers
**/
public void run()
{
// just let us know how many timers are running every 5 minutes
getSingleton().add(new Timer(300000)
{
@Override
public void execute()
{
System.out.println("[TimerExecutor] " + timers.size() + " timers running");
this.setTimeToRun(300000);
}
});

while (true)
{
synchronized(timers)
{
for (int i = 0; i < timers.size(); i++)
{
Timer t = timers.get(i);

try
{
if (t == null) // precautionary
{
System.out.println("[TimerExecutor] Null Timer removed");
timers.remove(t);
continue;
}
if (t.stop())
{
t.execute();
}

if (!t.isActive())
timers.remove(t);
}
catch (Exception e)
{ timers.remove(t); }
}
}
}
}
}

Step 2: Now we need to add the Timer class that this uses
Create a new Java file and put this in it:


package eu.util;

/**
* @name Timer.java
* @author tj007razor
*/

public abstract class Timer {
private long timeToRun; // time to run (in ms)
private long startTime; // the time the timer started at
private boolean activeTimer; // is the timer currently active?

/**
* constructor sets up the amount of time to run and converts input from seconds to ms, gets the starting time of the timer, and sets the timer as active
* @param timeToRun The amout of time for the timer to run for (in ms)
**/
public Timer(long timeToRun)
{
this.timeToRun = timeToRun;
startTime = getStartTime();
activeTimer = true;
}

/**
* constructor sets up a Timer that has no specific time to run, but is active
* @param activeTimer Timer is active or not
**/
public Timer(boolean activeTimer)
{
timeToRun = 0;
startTime = 0;
this.activeTimer = activeTimer;
}

/**
* default constructor which initializes the variables to 0 and false(for the boolean)
**/
public Timer()
{
timeToRun = 0;
startTime = 0;
activeTimer = false;
}

/**
* determines the starting time of the timer
* @return the starting time of the timer
**/
private long getStartTime()
{
return System.currentTimeMillis();
}

/**
* calculates the amount of time that has passed since the start of the timer
* @return the amout of time has passed since the timer started
**/
private long timeSinceStart()
{
return System.currentTimeMillis() - startTime;
}

/**
* @return whether the timer is active or not
**/
public boolean isActive()
{
return activeTimer;
}

/**
* set whether the timer is active or not
* @param activeTimer is the timer active?
**/
public void setActive(boolean activeTimer)
{
this.activeTimer = activeTimer;
}

/**
* set the amount of time for the timer to run and gets the starting time of the timer
* @param timeToRun The amout of time for the timer to run for (in ms)
**/
public void setTimeToRun(long timeToRun)
{
this.timeToRun = timeToRun;
startTime = getStartTime();
}

/**
* @return how much time is left for the timer(in ms)
**/
public long getTimeLeft()
{
return misc.round((double)((timeToRun - timeSinceStart())));
}

/**
* determines whether or not the timer is finished running
* @return if the timer is finished running
**/
public boolean stop()
{
if (timeSinceStart() >= timeToRun)
return true;
return false;
}

/**
* Execute the timer
**/
public abstract void execute();
}

Step 3: Now we need to figure out how this works
To make a Timer that does something, you follow this basic format:


TimerExecutor.getSingleton().add(
new Timer(time to run for in ms)
{
@Override
public void execute()
{
// do stuff here
}
});

Now, there's two things you can do from here. You can make it be repeating, or make it just run once. To only execute once, call setActive(false), that will make it be removed from the TimerExecutor's list of timers to process. IE:


TimerExecutor.getSingleton().add(
new Timer(time to run for in ms)
{
@Override
public void execute()
{
// do stuff here
this.setActive(false);
}
});

To make it repeat, you need to set the time for it to run again so it knows how long to run for the next time.


TimerExecutor.getSingleton().add(
new Timer(time to run for in ms)
{
@Override
public void execute()
{
// do stuff here
this.setTimeToRun(time to run for in ms);
}
});

So now we put it together. Lets say we want to do something every 10 seconds, you would do


TimerExecutor.getSingleton().add(
new Timer(10000)
{
@Override
public void execute()
{
// do stuff here
this.setTimeToRun(10000);
}
});

An example of this could be news announcements (lets say print every minute. This would look something like(in client):


TimerExecutor.getSingleton().add(
new Timer(60000)
{
@Override
public void execute()
{
sendMessage("[NEWS] Some server news is happening.")
this.setTimeToRun(60000);
}
});

Of course you'd want to make an array and roll through all announcements you want but I don't need to go into that for this tutorial.

Now how about after 10 seconds, do something once


TimerExecutor.getSingleton().add(
new Timer(10000)
{
@Override
public void execute()
{
// do stuff here
this.setActive(false);
}
});

An example of this could be mining a rock. When you click said rock,


TimerExecutor.getSingleton().add(
new Timer(5000) // takes 5 seconds to mine the rock
{
@Override
public void execute()
{
addItem(ore, 1);
addSkillXP(xp amount, 14);
sendMessage("You mine some " + name of ore mined + ".");
this.setActive(false);
}
});

Again, this is of course very simple and not meant to really anything, just shows possibilities of uses of this.

aTime
June 24th, 2010, 07:39
What the hell, why does everyone create these grand shitty systems when theres the TimerTask,

Only the registered members can see the link.

I'mWhite
June 24th, 2010, 07:42
good release, what you mean with timertask?

aTime
June 24th, 2010, 07:47
good release, what you mean with timertask?

The system is unfortunately unneeded



new Timer("timer").scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
}, 0, 1000);

Trey
June 24th, 2010, 15:44
What the hell, why does everyone create these grand shitty systems when theres the TimerTask,

Only the registered members can see the link.

That or people could just the enormous assortment of Executors and ExecutorServices.

samuraiblood2
June 24th, 2010, 15:56
What the hell, why does everyone create these grand shitty systems when theres the TimerTask,

Only the registered members can see the link.

You need to get with the times.

Only the registered members can see the link.

Fenway`
June 24th, 2010, 20:47
You need to get with the times.

Only the registered members can see the link.

thanks. studying up