First of all, to all of you reading this and new to Java and/or L2J, L2J has a class already made to handle timers/tasks. This class is called ThreadPoolManager.
I will not get into details as to how it works since this is meant to be a newbie tutorial, so just see the ThreadPoolManager as something that can allow you to set timers and repeating timers for specific tasks.
1- What do I need to know to make the ThreadPoolManager work for me?
Nothing too fancy really. The one thing that you need to know is that the task you want to perform needs to be a Runnable task(I will explain in a minute what this is and how to set it up). Except for this, there is really nothing complicated to know.
2- Runnable tasks:
A Runnable task is basically a small class which implements the Runnable class. For those of you who read my Java 101 tutorial, it's what I called a threadable task.
Lets create a simple one as an example:
Code: Select all
class MyTask implements Runnable{ public void run() { // You put your actions here }}
The ThreadPoolManager is made to handle many different variations of scheduled tasks, we will cover 2 here, a simple scheduled task and a repeating scheduled task.
First lets see a normal scheduled task which will execute only once.
This is the method we will use:
Code: Select all
ThreadPoolManager.getInstance().scheduleGeneral(Runnable, delay)
Obviously we now need to pass into it the runnable we want to use, lets take our MyTask example, it would give something like this:
Code: Select all
ThreadPoolManager.getInstance().scheduleGeneral(new MyTask(), 5000);
Now, lets say we want this task to run each 5 seconds in a continuous loop.
We have this method in ThreadPoolManager which can help:
Code: Select all
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(Runnable, initial, delay)
Code: Select all
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new MyTask(), 5000, 5000);
3- Passing variables to a Runnable task:
Our Runnable tasks can perform all sorts of tasks, some of which need to have specific parameters or need to affect something in particular, which is why we often want to pass to the task some informations and/or variables.
Lets use the MyTask example again but expand it a little bit:
Code: Select all
class MyTask implements Runnable{ private L2PcInstance player; public MyTask(L2PcInstance p) { player = p; } public void run() { player.breakAttack(); }}
It would look something like this:
Code: Select all
ThreadPoolManager.getInstance().scheduleGeneral(new MyTask(player), 5000);
I could go much more in depth with timers, but I feel that this is enough for most people who are learning L2J development to get them started. Have fun!