1. Timer use
Partial classTimerservice:servicebase { PublicTimerservice () {InitializeComponent (); } Timer Timer=NewTimer (); protected Override voidOnStart (string[] args) { //TODO: Add code here to start the service. Addlog ("* * * Service started"); Timer. Elapsed+=timer_elapsed; Timer. Interval= +; Timer. Start (); } intNumber =0; voidTimer_elapsed (Objectsender, Elapsedeventargs e) { Try{ number++; Addlog ("Section"+ number +"Secondary Execution Method"); Addlog ("Current Time:"+DateTime.Now.ToLongTimeString ()); } Catch(Exception) {}}protected Override voidOnStop () {//TODO: Add code here to perform the close operation required to stop the service. Addlog ("* * * Service terminated"); Timer. Stop (); } Public voidAddlog (stringstr) { using(StreamWriter SW =NewStreamWriter (@"G:\log.data",true) ) {SW. WriteLine ("****************************************"); Sw. WriteLine (str); } } }
2. Logging and database access
Partial classmessageboxser:servicebase {Thread mainthread; PublicMessageboxser () {InitializeComponent (); Mainthread=NewThread (NewThreadStart (ThreadFunc)); Mainthread.priority=Threadpriority.normal; } Public Static voidThreadFunc () {//While (true)//{ //Thread.Sleep (1000); //MessageBox.Show ("asdfasdf"); //} while(true) { //MessageBox.Show ("asdfasdf");Thread.Sleep ( the); //Modify DatabaseSertableda.adddata (); //Record Log//Try//{ //using (StreamWriter SW = new StreamWriter (@ "G:\log.data", true))// { //SW. WriteLine (DateTime.Now.ToLongTimeString () + "Execute loop Code"); // } //} //catch (Exception ex)//{ //} } } protected Override voidOnStart (string[] args) { //TODO: Add code here to start the service. Mainthread.start (); } protected Override voidOnStop () {//TODO: Add code here to perform the close operation required to stop the service. Mainthread.abort (); } }