I know I am probably way off here, but I am trying to create a timer array so that mytimer[0] mytimer[1], mytimer[2], etc... all fire off at a different interval, with diffrerent events sent to a server. Any ideas? The for loop value of 6 is an organic number for testing purposes only. This number would later be decided base on a setting from the program's xml file.
Timer mytimers[] = new Timer[6];
for(int i = 0;i < 6;i++){
final int mytime = i;
mytimers[i].scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//do action
sendData("Timer " + mytime + " fired");
}
}, 10000, i*1000);
}
Timer mytimers[] = new Timer();
I'm assuming this is the line that doesn't work? You can't initialize an array with an object; initialize it with an array:
Timer mytimers[] = new Timer[6];
Making another guess, you're also not initializing the individual timers:
mytimers[i].scheduleAtFixedRate(new TimerTask() {
At this point mytimers[i] isn't set to anything, so how can you call scheduleAtFixedRate on it? Initialize it first:
mytimers[i] = new Timer();
mytimers[i].scheduleAtFixedRate(new TimerTask() {
EDIT:
Your "IllegalArgumentException: Non-positive period." is because on the first time through the loop, i = 0, so i * 1000 = 0, and the period can't be 0 ("run this event every 0 zero seconds").
Start with i = 1 and it should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With