Here I will explain what windows service is, uses of windows service and how to create windows service in c#.
Description:
Today I am writing article to explain about windows services. First we will see what a window service is and uses of windows service and then we will see how to create windows service.
Creating Windows Service is very easy with visual studio just follow the below steps to create windows service
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ScheduledService() }; ServiceBase.Run(ServicesToRun); } |
using System.IO; using System.Timers; |
protected override void OnStart(string[] args) { } protected override void OnStop() { } |
//Initialize the timer Timer timer = new Timer(); public ScheduledService() { InitializeComponent(); } //This method is used to raise event during start of service protected override void OnStart(string[] args) { //add this line to text file during start of service TraceService("start service"); //handle Elapsed event timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); //This statement is used to set interval to 1 minute (= 60,000 milliseconds) timer.Interval = 60000; //enabling the timer timer.Enabled = true; } //This method is used to stop the service protected override void OnStop() { timer.Enabled = false; TraceService("stopping service"); } private void OnElapsedTime(object source, ElapsedEventArgs e) { TraceService("Another entry at "+DateTime.Now); } private void TraceService(string content) { //set up a filestream FileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write); //set up a streamwriter for adding text StreamWriter sw = new StreamWriter(fs); //find the end of the underlying filestream sw.BaseStream.Seek(0, SeekOrigin.End); //add the text sw.WriteLine(content); //add the text to the underlying filestream sw.Flush(); //close the writer sw.Close(); } |
Now the service is started, and you will be able to see entries in the log file we defined in the code.
Now open the log file in your folder that Output of the file like this
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|






Subscribe by RSS
Subscribe by Email
68 comments :
Gooood Article Suresh
Thanks Mehtab Keep visiting...
I always visit your site.....keep it up Suresh..:)
nice Article suresh
can we schedule our application daily on specific time using win services.
thank you
hi rajesh,
here if you observe this windows service will run for every one minute based on that you can adjust your time it will work for you
thanks and keep it up
Hi in my windows service in the onstart method im writing some data from one text file to other text file. so lets say it runs for every 5 mins i.e it keeps on checking for files in the dir every five min and then process...
so w.r.t to your above code done i need to write the same code in OnElapsedTime or is it fine if its just in onstart method(since after every 5 min the service starts from onstart method?
it's ok you can write your code in onstart method it will work for you. if you observe above code i used onstart method it will run for every one minute
Easy and informative samples.. thanks
Helpful article, thanks.
Thanks
Suri
Nicely Explained...KEEP IT UP :)
Hi suresh how r u...? your explaination is very nice...keep it up:)
nice example..
but i think u forgot to start the timer after assigning interval
sorry i missed that line
Hi suresh could you please suggest me..I want to implement a webservice to ping at each time interval like it will show a message box at each hour..So how to implement this?
I cant add message box..
its really very help full............
thanks suresh garu..............
Hi sir,
Please Answer this if you know My requirement is like this " I have folder in System when images copied into that folder that images names automatically inserted into database.
How can I do th is?
Regards
VeerendraNadh
@VeerendraNadh...
if your using application to save images in folder check this link
http://www.aspdotnet-suresh.com/2011/03/how-to-save-images-into-folder-and.html
if your directly copying the images into folder then you need to insert image names automatically into database then you need to write windows service to check all the images in folder and save those names in database
Thank you. really nice article.
excellent share!
Great post. Very interesting to see. I usually do not read blog, but this post definatelly caught my attention.
Nice work, is there a way to log as user, giving the username and password.
very nice article,
thanks for sharing...
keep it up well done nicely explained
hi suresh sir, this is very easy to learn to newer. very nice explanation.
sir my requirement is i have to insert record from one table to another table at particular interval. please answer if any solution/idea
thanks
Thank You!! :) Its really great suresh...
nice article
gr8 Suresh... ths article really helped me a lot..
hey iam using windows service to insert record from one to another table on particular interval but it eats lots of memory when i run ths service under services.msc... any solution to flush the memory used by ths service.Thanks!
Hi, This tutorial is relay helpful. But I want to read data from access DB using timer. I write code in OnElapsedTime() and also try onStart() but still got error. It was "the service on local computer started and then stopped. some services stop automatically...". Please tell me what's the problem. I clear my log file also and googling lot of blogs. Please help me.
suresh can u tel me how to send automatic email notification on weely bases or daily for multiple recipients ....
Thanks ! Good post suresh
Hi Suresh,
I want to implement timer in asp.net
so that user can see how much time is left for his test to complete
I want to set timer for 30 mins to complete online test.
can you please help me ?
I created a server in C# with the services it provides furnished
as a
WellKnownServiceTypeEntry,
and used
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType()
to make it available to clients over the network.
It works fine when the server is made as a console application, but doesn't work when the server is made as a Windows service. Please advise.
The Windows service runs as LocalSystem, was created in Visual Studio 2012. Firewall has been disabled.
Gud 1
Hi sir
In Windows service, how to display popup alert or system tray alert. Please give some ideas sir
nice... simple & clear
SIR,
my project has a module of silent remote installation of software on client machine from server. consider that the installation on client is going on from server and suddenly the server goes down and client is no more reciving any traffic from server then i want to write a service onto client machine that will continuously keep on analyzing the traffic coming from server and when it recieves no packets from server it should call recovery routine i.e resend the request to server to start the fresh installation.....
can u plz help me out with code for this service or guide for it.....
plz take my request into consideration and help me out at soonest...
Thank you.
Hi,Suresh
Very Nice and Impressive artical for begginers.
Now, I want to execute the stored procedure for every 5minutes which have the one out put parameter. So that where i need the call the procedure from the above code.
please help
thnaks in advance
Srikanth
very Good Support My Heart Full Thanks By KANNAN
hello sir,
i created one GUI application, now i want that application run as windows service.. meaning it should start when system is started , how to make my application run as i told above??
regards,
harini bangalore
this is very useful information
Hi suresh,
Nice blog.. really helped me out
vidur:nice one
Now Its Working fine...Thanks..
Very useful , your site willing to learn new stuff. Thank you.
Hello all,I am new and I would like to ask that what are the benefits of sql training, what all topics should be covered and it is kinda bothering me ... and has anyone studies from this course wiziq.com/course/125-comprehensive-introduction-to-sql of SQL tutorial online?? or tell me any other guidance...
would really appreciate help... and Also i would like to thank for all the information you are providing on sql.
its really very help full...
but I want to take backup of my database Every Day ,I need to write Windows Service,Give Code for that in C# . please...
thanks
Thanks so much for sharing.
Hai!! Thanks alot for your articles..:)God Bless
my requirement is: create windows service to run daily ONCE c#, fetch records from DB and export records to excel and send email that excel as a attachment. Please do the needful.
HI Suresh,
Could u please explain how to debug window service by step by step.
Thanks in adv.
-MadhuKrishna
Hi Suresh,
It was a wonderful tutorial. I had just one problem. Service couldn't write to text file. Although same code worked in Windows Form Application. Please help me out.
Thanks
Error 2 Unable to copy file "obj\x86\Debug\WindowsService1.exe" to "bin\Debug\WindowsService1.exe". The process cannot access the file 'bin\Debug\WindowsService1.exe' because it is being used by another process. WindowsService1
Gaurav Sharma Please help the solve the error
hi suresh...
I am getting Bad image format exception at the time of installation what i have to do pls help me..
sir i have made service build it and also run it
it is displayed in the list of the services but sir when i start the service in will give give the error "Could Not Start the Winservice service on local computer
Error 1067: the process terminated Unexpectedly."
my service name is Winservice
sir whats gone wrong ?
Hi Suresh...Nice article....I want to ask can we use this for ASP.NET application? Means I want to ask that consider a web page or application that is using windows service for printing tasks..
thanks and regards
Archit
Good article...! Neatly explained..
how do i get the user's entry out time automatically???? for example : like LOGIN time and LOGOUT time...
how do i get the user's entry out time automatically???? for example : like LOGIN time and LOGOUT time...
Hello Sir i have problem in start the service...my code is...
-------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
namespace Database_Configuration_Wizard
{
partial class DBConfigService : ServiceBase
{
Timer timer = new Timer();
MsAccess acce = new MsAccess();
public DBConfigService()
{
InitializeComponent();
}
//public void onCall()
//{
// this.OnStart(null);
//}
protected override void OnStart(string[] args)
{
this.GetData();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 10000;
timer.Enabled = true;
// TODO: Add code here to start your service.
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
GetData();
}
public DataTable GetData()
{
DataTable data = new DataTable();
acce.testConn(Properties.Settings.Default.ConnString);
data = acce.getTable("SELECT Employee_Info.EmpName, RFID_ATTEN.EnteryDate, RFID_ATTEN.RFIDReaderIp FROM Employee_Info INNER JOIN RFID_ATTEN ON Employee_Info.EmployeeId = RFID_ATTEN.EmployeeId");
acce.testConn(Properties.Settings.Default.DBbackup);
foreach (DataRow row in data.Rows)
{
int i = acce.excuteQuery("INSERT INTO Attendances ([employee_code],[name_date],[action_event]) VALUES ('" + row[0] + "','" + row[1] + "','" + row[2] + "')");
}
return data;
}
protected override void OnStop()
{
timer.Enabled = false;
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
please give suggestion asap....
thanks in advance....
Hi,
Currently i do have a requirement to develop a console based windows application which will check the status of all scheduled jobs scheduled in windows task scheduler and based on the job status it will fire email .
Anyone have any idea on this please.
Many Thanks,
Sisir
Hi,
I do have requirement which is of two parts :
1.Need to schedule a job in remote machine.Get all scheduled jobs in windows task scheduler and check the status of them.
2.Send alert email based on the job status(whether ran successfully or failed),
Any suggestion on this please.
Many Thanks,
Sisir
Hi,
can you tell me how to send email automatically in windows application based on the date specified in database.
ie,database table named sponser has 2 columns named sponsershipdate and type,by comparing these two values i have to send email automatically
How to attach pink-sound in mailing system in asp.net