I thought this was an interesting question, and although I don't quite understand your explanation about the function that executes every second but calls another function that runs for five seconds, it seems to me that the piece you're missing is how to encapsulate a method call. So I whipped up this sample that uses a timer and Action
delegates that are called at predetermined timer ticks. You should be able to extrapolate this into your design if it's what you're looking for.
class TimedFunction
{
public Action<TimedFunction, object> Method;
public int Seconds = 0;
public TimedFunction() {
}
}
class Program
{
static int _secondsElapsed = 0;
static List<TimedFunction> _funcs = new List<TimedFunction>();
static int _highestElapsed = 0;
static Timer _timer;
static void Main(string[] args) {
var method = new Action<TimedFunction, object>((tf, arg) => Console.WriteLine("{0}: {1}", tf.Seconds, arg));
_funcs.Add(new TimedFunction() { Seconds = 5, Method = method });
_funcs.Add(new TimedFunction() { Seconds = 8, Method = method });
_funcs.Add(new TimedFunction() { Seconds = 13, Method = method });
_funcs.Add(new TimedFunction() { Seconds = 10, Method = method });
_highestElapsed = _funcs.Max(tf => tf.Seconds);
_timer = new Timer(1000);
_timer.Elapsed += new ElapsedEventHandler(t_Elapsed);
_timer.Start();
Console.WriteLine();
Console.WriteLine("----------------------");
Console.WriteLine("Hit any key to exit");
Console.ReadKey(true);
}
static void t_Elapsed(object sender, ElapsedEventArgs e) {
_secondsElapsed++;
foreach (TimedFunction tf in _funcs) {
if (tf.Seconds == _secondsElapsed) {
tf.Method(tf, DateTime.Now.Ticks);
}
}
if (_secondsElapsed > _highestElapsed) {
Console.WriteLine("Finished at {0} seconds", _secondsElapsed - 1);
_timer.Stop();
}
}
}
This is the output:
----------------------
Hit any key to exit
5: 634722692898378113
8: 634722692928801155
10: 634722692949083183
13: 634722692979496224
Finished at 13 seconds
(this works because the timer is still running while the console is waiting for a keypress)
Note that while I used the same Action
delegate instance for all the TimedFunction
objects, nothing prevents you from using different ones. While you do need to define the types of arguments the delegates will take, you can always just use object
or some other type and pass in whatever you need.
Also, there's no error checking and you didn't mention what type of application you're doing this in; you'll probably want to use a separate thread, for example. Oh, and timer resolution isn't really that good so be careful.
Hope this helps.