Loading..
 

Task Scheduler, Periodic execution in asp.net c# by using Thread

In asp.net there are needs for performing few activities periodically.

For that we can use some class libraries or third party component to schedule a task or function to execute periodically.

Recently i found following simplest way to execute periodically any code.

Suppose you have a class and routine as follow in App_Code/CS,

public class ClassABC

{

public static void SomeFunctionToRunPeriodically()

{

try {

System.IO.File.WriteAllText(System.Web.Hosting.HostingEnvironment.MapPath(“~/LatestRunSaved.txt”), “Last Run of function at : ” + DateTime.Now.ToString() + Environment.NewLine);

}

catch (Exception ex) { string t = ex.Message; }

System.Threading.Thread.Sleep(20000);

SomeFunctionToRunPeriodically(); //calling self after interval

}

public ClassABC()

{ // // TODO: Add constructor logic here // }

}

 

If you notice in above function then its calling to itself after interval. Now in global application file ‘global.asax’ inside application start event use following lines to create a new thread based call to a function above.

void Application_Start(object sender, EventArgs e)

{

System.Threading.Thread obj = new System.Threading.Thread(new System.Threading.ThreadStart(ClassABC.SomeFunctionToRunPeriodically));

obj.Name = “AnyTestName”;

obj.IsBackground = true;

obj.Start();

}

New thread based function call will run until your application is running in IIS process, It is a background process. Other routine things on site will work normally without problem.



On, 27/07/2013, 27 July, 2013

Latest News

Facebook sued over video viewing figures
Tiny companion phone released in Japan
Amazon creates 1,000 'highly skilled' jobs in three UK cities
'Why we faked our Facebook wedding in Kinshasa'
Mitsubishi windows shine 'alarmingly realistic' fake sunlight
Grand Theft Auto 'cheats' homes raided
Twitter's 'Russia-Iran' troll tweet trove made public
Google unshackles Android-device firms
eBay files lawsuit against Amazon over 'seller recruitment'
Spotify ad banned for causing 'distress' to children