How can we use Asp.net on the server to regularly execute tasks without installing Windows service? We often need to run some maintenance tasks or scheduled tasks such as sending reminders to users. These can only be done by using Windows service. Asp.net is usually a stateless providerProgram, Does not support continuous operationCodeOr you can regularly execute a code segment. Therefore, we have to build our own Windows service to run those scheduled tasks. However, in a shared hosting environment, we do not always have the opportunity to deploy our own windwos service to the Web server of our hosting service provider. We either buy a dedicated server, which of course is very expensive, or sacrifice some features of our website. However, running a scheduled task is a very useful feature, especially for users who need to send reminders, administrators who need to maintain reports and run cleanup operations. I will show you a way to avoid using any windows
Service. Only Asp.net is used to run scheduled tasks.
How it works
First, we need some "scenarios" in Asp.net to continuously run and give us a callback. The Web server on IIS is a good choice. Therefore, we need to obtain the callback from it "frequently", so that we can view a task queue and see whether a task needs to be executed. Now, there are some ways for us to get the "Operation Right" for the Web Server ":
(1) When a page is requested
(2) When an application is started
(3) When an application is stopped
(4) When a session is enabled, ended, or timed out
(5) When a cache item fails
A page is requested randomly. If no one visits your site within several hours, you cannot complete any "task" within several hours ". In addition, the execution time of a request is very short, and the faster the request itself, the better. If you plan to execute "scheduled tasks" during page requests, the page will be forced to execute for a long time, which will lead to a bad user experience. Therefore, it is not a good choice to choose the time of page request.
A page is requested randomly. If no one visits your site within several hours, you cannot complete any "task" within several hours ". In addition, the execution time of a request is very short, and the faster the request itself, the better. If you plan to execute "scheduled tasks" during page requests, the page will be forced to execute for a long time, which will lead to a bad user experience. Therefore, it is not a good choice to choose the time of page request.
When a program is startedApplication_startThe method provides a callback. This is a good place to enable background threads. Background threads can run permanently to execute "scheduled tasks ". However, when the threadWebWhen the server is "Resting" for a while due to zero load, it may be "killed" at any time ".
When an application is stopped, we can also get a callback from the application_end method. But we can't do anything here, because the whole program is about to end running. Session_start in global. asax is triggered when a user accesses a page that needs to be instantiated as a new session. This is also a random event. However, we need a "scenario" that can run on a persistent and regular basis ".
The expiration time of a cache item can be a time point or duration. InAsp.netYou canCacheAdd an object to the object, and set an absolute expiration time, or set it to expire when it is removed from the cache. You can use the followingCacheTo do this:
Public void insert (system. string key, system. object value, <br/> system. web. caching. cachedependency dependencies, <br/> system. datetime absoluteexpiration, <br/> system. timespan slidingexpiration, <br/> system. web. caching. cacheitempriority priority, <br/> system. web. caching. cacheitemremovedcallback onremovecallback)
OnremovecallbackIs a method delegate that is called when a cache item fails. In this method, we can do anything we want to do. Therefore, this is a good candidate for regular and continuous code execution without any page requests.
This means that we can simulate a simple Windows service when a cache item fails.
Callback for creating cache items
First, in application_start, We need to register a cache item and invalidate it after two minutes. Note that the minimum value of the callback expiration time is two minutes. Although you can set a smaller value, it does not seem to work. The biggest possible cause of this problem is that the Asp.net workflow checks the cache items every two minutes.
Private const string dummycacheitemkey = "gagagugugigi"; </P> <p> protected void application_start (Object sender, eventargs e) <br/>{< br/> registercacheentry (); <br/>}</P> <p> private bool registercacheentry () <br/>{< br/> If (null! = Httpcontext. current. cache [dummycacheitemkey]) return false; </P> <p> httpcontext. current. cache. add (dummycacheitemkey, "test", null, <br/> datetime. maxvalue, timespan. fromminutes (1), <br/> cacheitempriority. normal, <br/> New cacheitemremovedcallback (cacheitemremovedcallback); </P> <p> return true; <br/>}
The cached object is a virtual object. We do not need to store any valuable information here, because whatever we store here, they may be lost when the application is restarted. In addition, all we need is to make frequent callback for this item.
Within the callback, we can complete the "scheduled task ":
Public void cacheitemremovedcallback (string key, <br/> object value, cacheitemremovedreason reason) <br/>{< br/> debug. writeline ("cache item callback:" + datetime. now. tostring (); </P> <p> dowork (); <br/>}
Store cache items again when the cache item fails
No matter when the cache item expires, we can get a callback and the item will permanently disappear from the cache. Therefore, we will not be able to get the callback again. To provide a continuous callback, we need to re-store a cache item before the next invalidation. This seems quite easy: we can call the registercacheentry method shown above in the callback function. Can we do this? It won't work! When a callback occurs, httpcontext is no longer accessible. Httpcontext can be accessed only when a request is being processed. Because callback occurs behind the scenes of the web server, no requests need to be processed, so the httpcontext object cannot be obtained. Therefore, you cannot access the cache object from the callback.
The solution is that we need a simple request. We can use the WebClient class in. netframework to implement a "virtual" access to a virtual page. When the virtual page is executed, we can hold the httpcontext object and register a callback for the cache item again.
Therefore, the callback method is modified to make a virtual call.
Public void cacheitemremovedcallback (string key, <br/> object value, cacheitemremovedreason reason) <br/>{< br/> debug. writeline ("cache item callback:" + datetime. now. tostring (); </P> <p> hitpage (); </P> <p> // do the service works </P> <p> dowork (); <br/>}
The hitpage method calls a virtual page:
Private const string dummypageurl = <br/> "http: // localhost/testcachetimeout/webform1.aspx"; </P> <p> private void hitpage () <br/>{< br/> WebClient client = new WebClient (); <br/> client. downloaddata (dummypageurl); <br/>}The application_beginrequest method is called no matter when the virtual page is called. There, we can check whether it is a "virtual" page.
Protected void application_beginrequest (Object sender, eventargs e) <br/>{< br/> // If the dummy page is hit, then it means we want to add another item </P> <p> // in cache </P> <p> If (httpcontext. current. request. URL. tostring () = dummypageurl) <br/> {<br/> // Add the item in cache and when succesful, do the work. </P> <p> registercacheentry (); <br/>}< br/>}
We only intercept requests from virtual pages, and let other pages continue to be executed in their original way.
Restart cache item callback when Web process restarts
In many cases, the web server may be restarted. For example, if the system administrator restarts IIS, or restarts the computer, or the web process is in an endless loop (in Windows 2003 ). In this case, the Service stops running until a page is requested and application_start is called. Application_start is called only when a page is accessed for the first time. Therefore, when a Web process is restarted, to enable the "service" to run, we can only manually call the "virtual" page or someone needs to visit the home page of your site.
A "slide" solution is to add search engines to your site. Search engines often crawl pages. Therefore, they will access a webpage on your site, which can trigger the execution of application_start, so the service will be started again.
Another solution is to register your site with some communication or availability monitoring services. There are many Web services that focus on your site and can check whether your site is normal and has good performance. All these services need to access the pages of your site and collect statistics. Therefore, by registering such a service, you can ensure that your site remains "alive.
Type of the test executable task
Let's test whether we can perform all the tasks that windowsservice can do. First, the first problem is that we cannot do everything that Windows service can do, because Windows service runs under the permission of a local system account. This is an account with high permissions. You can use this account to do anything in your system. However, the Asp.net web thread runs under the ASPNET account (Windows XP) or NetworkService account (Windows 2003 ). This is an account with low permissions and has no access to the hard disk. To allow services to write data to hard disks, Web processes must be granted write permissions on folders. We all know about this security issue, so I will not detail it in detail.
Now we will start to test what we usually do with windowsservice:
(1) writing to a file
(2) Database Operations
(3) web service call
(4) MSMQ operations
(5) email sending
Let's write some test code:
Private void dowork () <br/>{< br/> debug. writeline ("begin dowork... "); <br/> debug. writeline ("running as:" + <br/> windowsidentity. getcurrent (). name); </P> <p> dosomefilewritingstuff (); <br/> dosomedatabaseoperation (); <br/> dosomewebservicecall (); <br/> dosomemsmqstuff (); <br/> dosomeemailsendstuff (); </P> <p> debug. writeline ("End dowork... "); <br/>}
Test file write operation
Let's test whether we can write something into a file. Create a folder on drive C and name it "Temp" (if the disk format is NTFS, allow the ASPNET/NetworkService account to write to the folder ).
Private void dosomefilewritingstuff () <br/>{< br/> debug. writeline ("writing to file... "); </P> <p> try <br/> {<br/> using (streamwriter writer = <br/> New streamwriter (@" C: \ temp \ cachecallback.txt ", true) <br/>{< br/> writer. writeline ("cache callback: {0}", datetime. now); <br/> writer. close (); <br/>}< br/> catch (exception X) <br/>{< br/> debug. writeline (x); <br/>}</P> <p> debug. writeline ("file write successful"); <br/>}
Open the file and you should see the following information:
Cache callback: 10/17/2005 2:50:00 PM <br/> cache callback: 10/17/2005 2:52:00 PM <br/> cache callback: 10/17/2005 2:54:00 PM <br/> cache callback: 10/17/2005 2:56:00 <br/> cache callback: 10/17/2005 2:58:00 <br/> cache callback: 10/17/2005 3:00:00 pm
Test Database Connectivity
Run the following code in your "tempdb" Database (you can also create your own database for testing)
If exists (select * From DBO. sysobjects where id = <br/> object_id (n' [DBO]. [aspnetservicelog] ') and <br/> objectproperty (ID, N 'isusertable') = 1) <br/> drop table [DBO]. [aspnetservicelog] <br/> go </P> <p> Create Table [DBO]. [aspnetservicelog] (<br/> [mesage] [varchar] (1000) <br/> collate SQL _latin1_general_cp1_ci_as not null, <br/> [datetime] [datetime] not null <br/>) on [primary] <br/> go
The above Code creates a table named aspnetservicelog. Remember, because the table is created in tempdb, the table disappears when SQL Server is restarted.
Next, grant the db_datawriter permission for the tempdb database to the ASPNET/NetworkService account. In addition, you can define more special permissions and only allow write permissions to tables.
Now, write down the Test method:
Private void dosomedatabaseoperation () <br/>{< br/> debug. writeline ("connecting to database... "); </P> <p> using (sqlconnection con = new sqlconnection (" Data Source "+ <br/>" = (local); initial catalog = tempdb; integrated Security = sspi; ") <br/>{< br/> con. open (); </P> <p> using (sqlcommand cmd = new sqlcommand ("insert" + <br/> "into aspnetservicelog values" + <br/> "(@ message, @ datetime) ", con) <br/>{< br/> cmd. parameters. add ("@ message", sqldbtype. (varchar, 1024 ). value = <br/> "Hi I'm the ASP net service"; <br/> cmd. parameters. add ("@ datetime", sqldbtype. datetime ). value = <br/> datetime. now; </P> <p> cmd. executenonquery (); <br/>}</P> <p> con. close (); <br/>}</P> <p> debug. writeline ("database connection successful"); <br/>}
This will generate some records in the log table. You can test whether the execution of the "service" is delayed. You should get a row of data every two minutes.
Test Mail Distribution
The most basic requirement for running a Windows service is to regularly send email reminders and status reports. Therefore, it is important to test whether an email can be sent like a Windows Service:
Private void dosomeemailsendstuff () <br/>{< br/> try <br/>{< br/> mailmessage MSG = new mailmessage (); <br/> MSG. from = "abc@cde.fgh"; <br/> MSG. to = "ijk@lmn.opq"; <br/> MSG. subject = "reminder:" + datetime. now. tostring (); <br/> MSG. body = "this is a server generated message"; </P> <p> smtpmail. send (MSG); <br/>}< br/> catch (exception X) <br/>{< br/> debug. writeline (x); <br/>}< br/>}
Please change from and to some valid addresses, and you should receive an email notification every two minutes.
Test MSMQ
Let's write a simple method to test whether we can directly access MSMQ from Asp.net:
Private void dosomemsmqstuff () <br/>{< br/> using (messagequeue queue = new messagequeue (msmq_name) <br/>{< br/> queue. send (datetime. now); <br/> queue. close (); <br/>}< br/>}
In addition, you can call the receive method of the queue to parse the messages to be processed in the queue.
Here, you must remember not to subscribe to the receive events in the queue. Because the thread may be killed at any time, and the Web server may be restarted at any time, a blocked receive will not work normally. In addition, if you call the beginreceive method to simultaneously block code execution until a message arrives, the service will be stuck and other code will not run. Therefore, in this case, you will have to call the receive method to parse the message.
Extended system functions
The Asp.net service can be used to expand pluggable tasks. You can introduce job queuing from the web page for such services to be executed on a regular basis. For example, you can put a Job Queue into a cache, And let "service" select a task and execute it. In this way, you can implement a simple task processing system in your Asp.net project.
Let's implement a simple job class that contains information about task execution.
public class job <br/>{< br/> Public String title; <br/> Public datetime executiontime; </P> <p> public job (String title, datetime executiontime) <br/>{< br/> This. title = title; <br/> This. executiontime = executiontime; <br/>}</P> <p> Public void execute () <br/>{< br/> debug. writeline ("executing job at:" + datetime. now); <br/> debug. writeline (Th Is. title); <br/> debug. writeline (this. executiontime); <br/>} on a simple ASPX page, we release a task into a global task. in the arraylist named _ jobqueue in asax.
<textarea readonly name="code" class="csharp">Job newjob = new job ("A job queued at:" + datetime. now, <br/> datetime. now. addminutes (4); <br/> lock (Global. _ jobqueue) <br/>{< br/> global. _ jobqueue. add (newjob); <br/>}</textarea> Therefore, tasks in the queue will be executed after 4 minutes. The code of this service is executed every two minutes. It checks the task queue and whether there are any tasks that are overdue and need to be executed. If any task is waiting, it will be removed from the queue and executed. The Service Code has an additional method called executequeuedjobs. This method executes scheduled tasks:
<textarea readonly name="code" class="csharp">Private void executequeuedjobs () <br/>{< br/> arraylist jobs = new arraylist (); </P> <p> // collect which jobs are overdue </P> <p> foreach (job in _ jobqueue) <br/>{< br/> If (job. executiontime <= datetime. now) <br/> jobs. add (job); <br/>}</P> <p> // execute the jobs that are overdue </P> <p> foreach (job in jobs) <br/>{< br/> lock (_ jobqueue) <br/>{< br/> _ jobqueue. remove (job); <br/>}</P> <p> job. execute (); <br/>}< br/>}</textarea>
Do not forget to lock the static "task set" because Asp.net is multi-threaded. In addition, the page will be executed on different threads, so it is possible to write data to the task queue at the same time.