Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,143,464 members, 7,781,344 topics. Date: Friday, 29 March 2024 at 12:49 PM

Java Coding Challenge: Task Scheduler - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Java Coding Challenge: Task Scheduler (8377 Views)

Mini Web Application Coding Challenge For Programmers / Coding Challenge 5: Substring Generator / Appointment Scheduler In Asp (2) (3) (4)

(1) (2) (Reply) (Go Down)

Java Coding Challenge: Task Scheduler by candylips(m): 10:00am On Aug 03, 2011
Implement a task scheduler that recursively schedules a task for execution at exponential time intervals up to a steady state. (i.e 1,2,4,8,16,32, , 900,900,900 in seconds.) steady state can be any number i.e 900 seconds.


The Task you pass to this scheduler can implement this interface

public interface Task {

void execute() throws Exception;

}
Re: Java Coding Challenge: Task Scheduler by candylips(m): 6:31pm On Aug 03, 2011
anyone good enough to take a shot at this  grin
Re: Java Coding Challenge: Task Scheduler by Fayimora(m): 8:47pm On Aug 03, 2011
[size=15pt]I dnt even understand it in the first place, lol You talking about something like a timer?[/size]
Re: Java Coding Challenge: Task Scheduler by Nobody: 9:02pm On Aug 03, 2011
LOl @ Fayimora.

@ CandyLips
I am coming up with a solution. Nice challenge by the way.
Re: Java Coding Challenge: Task Scheduler by candylips(m): 11:20pm On Aug 03, 2011
Fayimora:

[size=15pt]I dnt even understand it in the first place, lol You talking about something like a timer?[/size]

There are two parts to the question.

A scheduler that accepts a task.

A timer that runs this task at exponential time intervals.

So the first time the timer runs the task it will run it for 1 sec.

after the task finishes it should then rerun the task for 2 sec, then 4 sec until it gets to a steady state of 900 secs at which point it can stop.

An example practical use of this is as a simple retry algorithm for reconnecting to a lost database connection. You know typically you might have somewhere in you code that says if you lose db connection try to reconnect. if it fails wait for a few secs and retry again.
Re: Java Coding Challenge: Task Scheduler by Nobody: 11:45pm On Aug 03, 2011
/**
* Task.java
*
* Each task should implement this interface to provide
* its own unique behavior.
*/

interface Task
{
public void execute();
}

/**
* CandyLipsTask.java
*
* CandyLipsTask represents a common task for all the tasks this
* application will create. Of course, you can simply implement the
* interface Task if you want a unique behavior for each task.
*/

class CandyLipsTask implements Task
{
// The id of this task.
private final int taskID;

// The start date of the first task.
private java.util.Date startDate = null;

/**
* Construct a task for scheduling.
* @param taskID If this number is unique, then it identifies this task.
* @param startDate The start date of the first task.
*/

public CandyLipsTask(final int taskID, final java.util.Date startDate)
{
this.taskID = taskID;
this.startDate = startDate;
}

/**
* Our inherited function does not do much. It simply outputs when this
* task is running, relative to the first task.
*/

public void execute()
{
System.err.format("Task %3d : ", taskID);
System.err.format("%5d seconds have passed after scheduling started.%n",
((System.currentTimeMillis() - startDate.getTime()) / 1000));
}
}

/**
* CandyChallenge.java
* This contains our main class.
*
* A simple class to implement candylip's program challenge
* @see https://www.nairaland.com/nigeria/topic-726634.0.html#msg8844055
*/

public class CandyChallenge
{
// The non-daemon thread to schedule our tasks.
private java.util.Timer timer = new java.util.Timer(false);

// The current running task. Tasks are numbered starting from 1.
private int currentTask;

// The start date of the first task.
private java.util.Date startDate;

// The final task.
private int MAX;

/**
* Creates a new object that facilitates scheduling tasks at exponential
* times.
* @param startDate The start Date of the first task.
*/

public CandyChallenge(final java.util.Date startDate)
{
currentTask = 1;
this.startDate = startDate;
}

/**
* Schedules task to run from task currentTask and up to and including
* task MAX, where the start time of consecutive tasks increases
* exponentially.
* @see MAX
* @see scheduleTask
* @see currentTask
* @param taskStartDate The startDate of this task.
*
* @param interval The interval between this task and the next
* task. The interval between task x and task (x + 1)
* is 2^(x - 1) seconds.
* @param steadyState The interval between the final two tasks would be
* 2^x, where x is the greatest integral power of 2
* that is <= steadyState.
* @param tasks task[k] is the task for the (k + 1)th task.
*/

private void scheduleTask(final java.util.Date taskStartDate,
long interval,
final long steadyState,
final Task[] tasks)
{
// Schedules this task.
timer.schedule(new CandyLipsTimer(currentTask, tasks[currentTask - 1]),
taskStartDate);
++currentTask;

// Schedule another task if we haven't hit the maximum.
if(interval <= steadyState)
// Recursively call the next task.
scheduleTask(new java.util.Date(taskStartDate.getTime() +
interval * 1000), interval <<= 1, steadyState, tasks);
}

/**
* One timer runs each task.
*/

private class CandyLipsTimer extends java.util.TimerTask
{
// The task to run for this timer
private Task task;

// The id of this task.
private final int taskID;

/**
* Constructs a task which simply calls the run method when called by
* the timer.
*
* @param taskID The id of this task.
*/

public CandyLipsTimer(final int taskID, final Task task)
{
this.taskID = taskID;
this.task = task;
}

/*
* Run this task.
*/

public void run()
{
if(taskID == MAX)
timer.cancel();

task.execute();
}
}

/**
* Sets the start date of the first task.
*
* @param startDate The start date of the first task.
*/

public void setStartDate(java.util.Date startDate)
{
this.startDate = startDate;
}

/**
* Schedules tasks to run, from task 1 to task MAX.
* @param steadyState The interval between the final two tasks would be
* 2^x, where x is the greatest integral power of 2
* that is <= steadyState.
* @param tasks The tasks to run.
*/

public void scheduleTask(final long steadyState, final Task[] tasks)
throws Exception
{
MAX = CandyChallenge.getMAX(steadyState);
if(tasks.length < MAX)
throw new Exception("The tasks are too few");
scheduleTask(startDate, 1, steadyState, tasks);
}

/**
* Returns the maximum number of tasks for a given steady state.
*
* @param the steady state.
*/

public static int getMAX(final long steadyState)
{
return (int)(Math.log(steadyState) / Math.log(2)) + 2;
}

/**
* Informs the user of the application's correct usage.
*/

public static void usage()
{
System.err.println("\nUsage: java CandyLipsChallenge steadyState" +
" startDelay");
System.err.println(" steadyState The interval between the final two" +
" tasks\n would be 2^x, where x is the " +
"greatest\n integral power of 2 that" +
" is <= steadyState.");
System.err.println(" startDelay The delay between application" +
" startup and\n the first task " +
"execution.");
System.err.println(" Both arguments are in seconds and must be " +
"nonnegative.\n");
}

public static void main(String[] args) throws Exception
{
// Enfore the number of arguments passed to the application.
if(args.length != 2)
{
usage();
System.exit(1);
}

// The delay(in seconds) between the application startup and
// the first task execution.
int startDelay = 0;

/*
* The interval between the final two tasks would be 2^x, where x is the
* greatest integral power of 2 that is <= steadyState.
* steadyState is in seconds.
*/

int steadyState = 1;

// Make sure arguments are non-negative integers.
try
{
startDelay = Integer.parseInt(args[1]) * 1000;
steadyState = Integer.parseInt(args[0]);

if(startDelay < 0 || steadyState < 0)
throw new NumberFormatException();

}
catch(NumberFormatException ne)
{
usage();
System.exit(1);
}

// The start date of the first task.
final java.util.Date startDate = new java.util.Date((
new java.util.Date(System.currentTimeMillis()).getTime() +
startDelay));

Task[] tasks = new Task[CandyChallenge.getMAX(steadyState)];
for(int k = 0; k < tasks.length; )
tasks[k] = new CandyLipsTask(++k, startDate);

// Only run application if the steady state is greater than 0.
if(steadyState > 0)
new CandyChallenge(startDate).scheduleTask(steadyState, tasks);
}
}
Re: Java Coding Challenge: Task Scheduler by Nobody: 11:57pm On Aug 03, 2011
Usage: java CandyLipsChallenge steadyState startDelay
   steadyState The interval between the final two tasks
               would be x, where x is the greatest
               integral power of 2 that is <= steadyState.
   startDelay  The delay between application startup and
               the first task execution.
   Both arguments are in seconds and must be nonnegative.



Example:

  java CandyLipsChallenge 15 3

Re: Java Coding Challenge: Task Scheduler by Fayimora(m): 1:36am On Aug 04, 2011
[size=15pt]Woop! Nice code and documentation. This is obviously outta ma league for now. So whats happening exactly? sad [/size]
Re: Java Coding Challenge: Task Scheduler by Nobody: 6:51am On Aug 04, 2011
Ok. The goal of the application to run a couple tasks, with the constraint that the tasks start at increasingly exponential times until some steady state, which we shall call s. Suppose s = 20 seconds and you want the first task to start 3 seconds after the application starts, then you should enter:
   java CandyLipsChallenge 20 0
so that
   Task 2 should start at   0 + 2^0 =   1 seconds after task 1
   Task 3 should start at   1 + 2^1 =   3 seconds   "     "
   Task 4 should start at   3 + 2^2 =   7 seconds   "     "
   Task 5 should start at   7 + 2^3 =  15 seconds   "     "
   Task 6 should start at  15 + 2^4 =  31 seconds   "     "
Task 7 above will not run because it will occur after 31 + 2^5 = 63 seconds after the first task, that is the interval between task t and task 6 = 63 - 31 = 32 > s = 20. Note that the interval between any two consecutive tasks <= 20, but task 7 doesn't obey that rule, hence it wasn't scheduled to run. Now to the code.

Peruse through class CandyLipsTask. An object of this class is created for each task. For example task 2 will be created by this idiom: new CandyLipsTask(2), and when the timer schedules it to run, it will simply execute the run method in CandyLipsTask.
Re: Java Coding Challenge: Task Scheduler by candylips(m): 9:57am On Aug 04, 2011
very nice try omo_to_dun  grin

You are almost there. The intervals should be 1, 2 ,4 , 8 . . . you can calculate it by taking the square of the current Interval and pass as the next interval to the scheduler

The interface will make the implementation more generic.

I can see in your code that you just increment a taskId as the task.

If you use the interface, it will be possible to execute any logic within the execute method.

Let me give you a hint

public class GenericTask implements Task
{

    @Override
    public void execute()
    {
        System.out.println("Successfully ran genericTask!"wink;

    }

}


In Candylips task just pass in the constructed Generic Task and have it executed in the run method

i.e


public CandyLipsTask(int taskId,Task task)
    {
       this.taskID = taskID;
        this.task = task;
    }


public void run()
    {

        if (taskID == MAX)
            TIMER.cancel();

        task.execute();

        System.err.format("Task %3d : ", taskID);
        System.err.format("%5d seconds have passed after scheduling started.%n",
                ((System.currentTimeMillis() - STARTDATE.getTime()) / 1000));
    }


then in scheduleTask

  timer.schedule(new CandyLipsTask(currentTask++, new GenericTask()), taskStartDate);
Re: Java Coding Challenge: Task Scheduler by Shimao(m): 12:01pm On Aug 04, 2011
@Candylips, my sentiments exactly. Though a nice try, his task is tightly coupled to the scheduling system which makes is difficult to reuse say in an EJB or a custom scheduling framework. Essentially, the task should be modular and oblivious of the scheduling system. More so, a part of his code depends on proper usage by the user which can never be guaranteed. I would expect state checking to ensure that an possibly an IllegalStateException thrown. Good try though.
Re: Java Coding Challenge: Task Scheduler by Nobody: 3:23pm On Aug 04, 2011
@ candylips
The intervals are correct! I think you just looked at the raw numbers I posted. You didn't do the subtraction:

The interval bewtwen task 1 and task 2 =  1 - 0 = 1 sec
The interval bewtwen task 2 and task 3 =  3 - 1 = 2 sec
The interval bewtwen task 3 and task 4 =  7 - 3 = 4 sec
The interval bewtwen task 4 and task 5 = 15 - 7 = 8 sec

The times I showed are not intervals but the time elapsed after the first task.

I originally implemented the code using your interface but I removed it since I just wanted to make it smaller. Also, I thought that if someone can actually understand the code s/he can easily tweak it and execute any task.
Re: Java Coding Challenge: Task Scheduler by Nobody: 3:29pm On Aug 04, 2011
Shimao:

@Candylips, my sentiments exactly. Though a nice try, his task is tightly coupled to the scheduling system which makes is difficult to reuse say in an EJB or a custom scheduling framework. Essentially, the task should be modular and oblivious of the scheduling system. More so, a part of his code depends on proper usage by the user which can never be guaranteed. I would expect state checking to ensure that an possibly an IllegalStateException thrown. Good try though.

Of course, modularizing the code the above code is extremely trivial. Since the goal of the challenge was simply to solve the problem and not about best software engineering practices, hence, my result.
Re: Java Coding Challenge: Task Scheduler by Shimao(m): 3:44pm On Aug 04, 2011
I agree its trivial, but I believe thats what Candylips is trying to point out. Even though a programming challenge, how it is approached at first thought gives an idea about object orientation of the person. No offense intended.
Re: Java Coding Challenge: Task Scheduler by Nobody: 4:08pm On Aug 04, 2011
None taken at all.

I just wish others had posted their own codes.
Re: Java Coding Challenge: Task Scheduler by candylips(m): 4:12pm On Aug 04, 2011
@omo_to_dun

Thats correct i checked the code again i missed the part where you did the bitwise operation interval <<= 1

That effectively gets the expenential of the interval.

Great work !!

Anyone else want  to take  a shot at this before i post my solution   cheesy
Re: Java Coding Challenge: Task Scheduler by Nobody: 4:16pm On Aug 04, 2011
I'll make the adjustments that you prescribed. Thanks.
Re: Java Coding Challenge: Task Scheduler by Mobinga: 4:49pm On Aug 04, 2011
Brainphuck. cry
Re: Java Coding Challenge: Task Scheduler by Nobody: 5:17pm On Aug 04, 2011
@ candyLips

The code has been updated. Check it out. If you need the syntax highlighter for your solution please let me know.
Re: Java Coding Challenge: Task Scheduler by candylips(m): 5:57pm On Aug 04, 2011
Great Job !

its looking like you are the only one that will attempt this challenge

Yea i will need the syntax highlighter to post my solution
Re: Java Coding Challenge: Task Scheduler by Nobody: 6:20pm On Aug 04, 2011
For some reason, NL doesn't let us attach files with zip, jar, and other types of extensions. So I renamed my JavaSMF2.class to JavaSMF2.pdf to bypass that restraint. Kindly re-rename and run java on it. You should pipe your output to a txt file, lest it prints all the data to the screen. Simply copy the contents of that txt file into NL's message text area. Suppose that I want to syntax highlight myjavafile.java, I normally would enter:

   java JavaSMF2 myjavafile.java > smf.txt


And by the way, how come I have never seen you and Shimao on this board? You folks are good.

Updated:
I also noticed something. Since SMF uses the square brackets to enclose its elements(size, font, hr, i, b, etc), if you have an array in your code, make sure that you don't use a valid SMF element to index it. For example, I previously had task[i] in my code, but [i] in SMF will make everything italic up to the closest matching [/i]. So I changed it from task[i] to task[k]. Notice that, in writing this, I still had to make the i in the tag italic, lest the parser will italicize some of this text and the [i] and [/i] wouldn't even appear.

Re: Java Coding Challenge: Task Scheduler by Seun(m): 7:57pm On Aug 04, 2011
Don't distribute executables; distribute source code, so people can review. Beware of trojan horses.
Re: Java Coding Challenge: Task Scheduler by Nobody: 8:08pm On Aug 04, 2011
The file I distributed was a Java class that I wrote and compiled myself on a Linux machine. No Trojan Horse. I have distributed tons of jar files and classes on this site and no one has complained yet.
Re: Java Coding Challenge: Task Scheduler by Mobinga: 11:25pm On Aug 04, 2011
Besides I've never heard of viruses coded on java.
Re: Java Coding Challenge: Task Scheduler by Beaf: 4:50am On Aug 07, 2011
candylips:

Great Job !

its looking like you are the only one that will attempt this challenge

Yea i will need the syntax highlighter to post my solution

That might have a lot to do with your restricting the challenge to Java. In the meantime, we Java anti-evangelists be plenty indeed! grin
Re: Java Coding Challenge: Task Scheduler by Nobody: 4:52am On Aug 07, 2011
Then post it in C# or any other language that you prefer.
Re: Java Coding Challenge: Task Scheduler by Beaf: 4:54am On Aug 07, 2011
candylips: Implement a task scheduler that recursively schedules a task for execution at exponential time intervals up to a steady state. (i.e 1,2,4,8,16,32, ,  900,900,900 in seconds.) steady state can be any number i.e 900 seconds.


The Task you pass to this scheduler can implement this interface

public interface Task {

void execute() throws Exception;

}

Here's your solution in rebelious ol' C# (yeah, one for the C#, C++, C massive out deh). Short and sweet solution. Lol
You call it like this:

TaskScheduler.Create();


 
   public class TaskScheduler
   {
       public static int timeToRunTask = 1;
       public static int steadyStateSeconds = 900;
       public static void Create()
       {
           if (timeToRunTask < steadyStateSeconds)
           {
               CustomTask customTask = new CustomTask(timeToRunTask);
               customTask.Execute();
               timeToRunTask *= 2;
               Create();
           }
       }
   }

   public class CustomTask : ITask
   {
       public int TimeToRunTask;
       public CustomTask(int timeToRunTask)
       {
           TimeToRunTask = timeToRunTask;
       }
       public void Execute()
       {
           if(TimeToRunTask == 0)//any ol' test would do here. Lol!
               throw new Exception();
           //simulate task running for TimeToRunTask length of time
           //System.Threading.Thread.Sleep(TimeToRunTask * 1000);
           Console.WriteLine(TimeToRunTask);
       }
   }

   public interface ITask
   {
       void Execute();
   }
Re: Java Coding Challenge: Task Scheduler by Nobody: 5:29am On Aug 07, 2011
[list]
[li]Your steady state is hard-coded, hence is limited to 900 seconds.

[/li]
[li]Suppose I want to schedule, say, 10 tasks and I implement the ITask interface, I have no way of doing it because your TaskScheduler only schedules a CustomTask object not an ITask object.

[/li]

[li]You are simply printing the timeToRunTask variable, not the actual time at which a task starts.

[/li]

[li]Your approach is deeply flawed since if a task takes too much time to complete its instructions, it will result in eating other tasks' time since they are all scheduled on one thread.

[/li]

[li]It'd be nice to have a full application where folks can just copy and run on their systems without any modification whatsoever.

[/li]
[/list]
Re: Java Coding Challenge: Task Scheduler by Beaf: 5:54am On Aug 07, 2011
^
grin grin grin grin grin grin grin grin grin grin

How hard is it to be more wrong than you? Stop extending the question and bow down to a sweet, sexy solution that shows a lil bit of panties.
Re: Java Coding Challenge: Task Scheduler by Nobody: 6:05am On Aug 07, 2011
^
LOL @ Beaf. I ran your code and it is useless. I don't think you even understand the question. Nice try though. Go and learn more, and leave the coding to men. This is not the boys' zone. I am glad that you did not disagree with any of my points.
Re: Java Coding Challenge: Task Scheduler by Beaf: 6:12am On Aug 07, 2011
^
You're still the same ol' funny guy. This is what the challenge is:

There are two parts to the question.

A scheduler that accepts a task.

A timer that runs this task at exponential time intervals.

So the first time the timer runs the task it will run it for 1 sec.

after the task finishes it should then rerun the task for 2 sec, then 4 sec until it gets to a steady state of 900 secs at which point it can stop.

An example practical use of this is as a simple retry algorithm for reconnecting to a lost database connection. You know typically you might have somewhere in you code that says if you lose db connection try to reconnect. if it fails wait for a few secs and retry again.

. . .And I'm slam on 100%. It doesn't tell you what the tasks in question are (LOL!), just that they might implement an interface. All we need do, is provide the correct running time for each task. You made some wild assumptions and ended up with like 3 pages of code for what a few lines would have done.

Bow down to the code god, some (like me) are bound to be better than others.

While plotting your next reply, help yourself with this; http://en.wikipedia.org/wiki/Task_(computing)
Re: Java Coding Challenge: Task Scheduler by Nobody: 6:20am On Aug 07, 2011
Exactly. It does not tell you what kind of task. That is the key. Anyone can use my code, but not yours since it is tightly coupled. All they have to do is extend the interface Task and do

   new CandyChallenge(startDate).scheduleTask(steadyState, tasks);

where tasks is an array of objects created from the class which implemented Task. Anyway. it's nice to have you back on NL.

(1) (2) (Reply)

Java Vs C Sharp / How To Deploy Application With Access Database In Vb.net 2008 / Phpbrowserbox Update - Google Chrome + PHP/MySQL Server In One!

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 117
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.