I've created a simple daily task scheduler but I'd like to change this to a general task scheduler accepting more advanced schedules.
I'd like to have some critiques from other sets of eyes on my current implementation before I continue.
public class ScheduleJob
{
#region PRIVATE VARIABLES
private readonly Timer _timer;
private Action _job;
private int _setHour;
private int _setMin;
#endregion
#region CONSTRUCTOR
public ScheduleJob()
{
_timer = new Timer();
_setHour = 0;
_setMin = 0;
}
#endregion
#region PUBLIC METHODS
public void SetTimeofDay(int in_hour, int in_min)
{
_setHour = in_hour;
_setMin = in_min;
}
public void SetJob(Action in_task)
{
_job = in_task;
}
public void Start()
{
try
{
int PeriodMin = GetHour() * 60 + GetMin(); //minute
_timer.Interval = PeriodMin * 60 * 1000; //millisecond
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
IsRunning = true;
}
catch (Exception)
{
IsRunning = false;
}
}
public void Stop()
{
if (_timer != null)
_timer.Stop();
IsRunning = false;
}
#endregion
#region PRIVATE METHODS
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Enabled = false;
_job(); //perform the job
int PeriodMin = 24 * 60;
_timer.Interval = PeriodMin * 60 * 1000;
_timer.Enabled = true;
}
private int GetHour()
{
int _nowHour = DateTime.Now.Hour;
if (_nowHour > _setHour)
{
return (24 - (_nowHour - _setHour));
}
else
{
return (_setHour - _nowHour);
}
}
private int GetMin()
{
int _nowMin = DateTime.Now.Minute;
if (GetHour() == 0)
{
if ((_setMin - _nowMin) <= 0)
{
return (24 * 60) + Math.Abs(_setMin - _nowMin);
}
}
return (_setMin - _nowMin);
}
#endregion
#region PROPERTIES
public bool IsRunning { get; set; }
#endregion
}
-
1\$\begingroup\$ How about you start by running StyleCop on this and correcting the problems. This will find lots of stuff for sure. \$\endgroup\$Leonid– Leonid2012年06月15日 21:57:58 +00:00Commented Jun 15, 2012 at 21:57
-
\$\begingroup\$ The KetticScheduler view class provides Workday view to highlight working time in Windows application to set work scheduling. \$\endgroup\$user36938– user369382014年02月17日 08:21:57 +00:00Commented Feb 17, 2014 at 8:21
1 Answer 1
Just a small comment from me. I'm not so sure about the need for the method SetJob(). It seems like there is a requirement for this method to be called before the Start() and once called you wouldn't call it again?
Hence perhaps I might look at moving this to the constructor that would hopefully imply this concept? Also that way you can't change the job. This is of course made with the assumption you aren't looking at changing jobs once a new ScheduledJob has been setup.
Also probably what Stylecop might pick up anyway as suggested by Leonid;
- I personally wouldn't recommend using an _ for a variable within a method i.e. _nowMin
- Same applies for the private method _timer_elapsed()
-
\$\begingroup\$ Exactly what I would have said. \$\endgroup\$Konrad Rudolph– Konrad Rudolph2012年06月16日 09:36:42 +00:00Commented Jun 16, 2012 at 9:36