I am writing a service which requires multiple timers (system) to be created. The number of timers to create is not known until runtime, it’s based upon the contents on an external (XML) config file.
Each timer will be assigned a different task and a different interval.
How can I create x number of timers dynamically? I want to use a count from the for loop in the class instance name, but I don’t seem to be able to figure out how to do this.
Current code as below which creates one timer with the last result of the for loop. I want to create a timer for each loop.
I am learning C# so examples would be very helpful.
var items = GetDownloadList();
int CountDownloadListItems = DownloadItemsCount();
for (int i = 0; i < CountDownloadListItems; i++)
{
if (ClassLib.UrlExists.Check(items[i, 2], items[i, 0]))
{
//new instance of timers
Timers downloadTimer = new Timers();
downloadTimer.CreateTimer(items[i, 2], items[i, 3], items[i, 4], items[i, 0], items[i, 5], items[i, 6]);
}
}
// My Timers Class
public class Timers
{
//timer
private Timer _timer = new Timer();
private volatile bool _requestStop = false;
public Timers()
{
_timer.Interval = 20;
_timer.Elapsed += Timed;
_timer.AutoReset = false;
}
private string _Url;
private string _Save;
private string _File;
private string _Id;
private string _FreqValue;
private string _FreqUnit;
public string Url
{
get { return _Url; }
set { _Url = value; }
}
public string Save
{
get { return _Save; }
set { _Save = value; }
}
public string File
{
get { return _File; }
set { _File = value; }
}
public string Id
{
get { return _Id; }
set { _Id = value; }
}
public string FreqValue
{
get { return _FreqValue; }
set { _FreqValue = value; }
}
public string FreqUnit
{
get { return _FreqUnit; }
set { _FreqUnit = value; }
}
public void CreateTimer(string url, string save,string file,string id,string freqValue,string freqUnit)
{
this.Url = url;
this.Save = save;
this.File = file;
this.Id = id;
this.FreqValue = FreqValue;
this.FreqUnit = FreqUnit;
_timer.Interval = 2000;
_timer.Start();
}
private void Timed(object source, ElapsedEventArgs e)
{
_timer.Stop();
//StreamWriter sr = new StreamWriter("E:\\downloader\\"+Id+".txt");
//sr.Write(Url+" "+Save+" "+File+"\n\n");
//sr.Close();
ClassLib.Update.File(Url,Save,File,Id);
_timer.Start();
}
}
You do appear to be a creating a new
Timersfor each value in the for loop. However, you don’t appear to keeping a reference to them.How about adding a
Dictionary<string, Timers>variable that stores the references alonsgide the ‘name’?