Create A Windows Scheduler To Schedule A Web API Call - STW Services

Introduction 

 
In this article, we are going to learn how to call a web API from a windows service at a scheduled time.
 
We will create a sample ASP.NET Web API project and publish the project to IIS Manager. Once our API is completed, we will create a windows service that calls our Web API at a scheduled time. We will log the API calls in a text file from the Windows service.
 

Creating the API

 
Step 1
 
Open Visual Studio
 
Step 2
 
Create a New Project
 
 
Step 3
 
Select the ASP.NET Web Application Template (C#)
 
 
Step 4
 
On the next menu, we want to name our project "WebApi”
 
 
Step 5
 
Select the Web API template and select create.
 
Web api template
 
Once our web API is created successfully, we can go ahead and make simple customizations to the values controller.
  1. public IEnumerable < string > Get() {  
  2.     return new string[] {  
  3.         "Api Data 1",  
  4.         "Api Data 2"  
  5.     };  
  6. }   
We are done with our simple customizations let us publish our Web API to IIS (Internet Information Service)
 
You can skip this step as this is optional otherwise we can launch the API directly from visual studio and test our API.
 
Step 6
 
Create a publish profile.
 
Click on Build Tab and click Publish WebApi
 
 
On the next model, select Folder and enter the Folder location you wish to publish to.
 
 
Here we click the publish button.
 
 
Hosting the application in IIS
 
Open the IIS manager and select add a new application.
 
 
Afterward, add the name and path of our API on the next popup screen.
 
 
Once this is done, our API is now ready. We can call our API on the browser by running the URL like this.
 

Creating the windows service

 
We will create the project like we did the WebApi, but this time we will select the Windows service template.
 
 
We will name our WindowsServiceApiCaller
 
Our created service project looks like this:
 
 
Let us add an installer.
 
Right-click on the blank area and select Add installer.
 
Now we are going to customize the installer.
 
Right-click the serviceProcessInstaller1 on the designer and select properties.
 
 
On account select LocalSystem
 
 
We will also configure serviceInstaller properties like this
 
 
We are going to rename our service1 to WindowsApiCallService
 
 
Applying the code.
 
Right-click on the blank space of the designer and select view code.
 
This will take us to the code that looks like this.
 
 
Now we are going to make changes to the code. We will be using the following namespaces.
  1. using System;  
  2. using System.IO;  
  3. using System.Net;  
  4. using System.ServiceProcess;  
  5. using System.Timers;  
  6. namespace WindowsApiCallService {  
  7.     public partial class WindowsApiCallService: ServiceBase {  
  8.         Timer timer = new Timer();  
  9.         DateTime scheduleDateTime;  
  10.         public WindowsApiCallService() {  
  11.             InitializeComponent();  
  12.         }  
  13.         protected override void OnStart(string[] args) {  
  14.             WriteLogFile("Service is started");  
  15.             timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
  16.             scheduleDateTime = DateTime.Today.AddHours(16).AddMinutes(10);  
  17.             var scheduleInterval = scheduleDateTime.Subtract(DateTime.Now).TotalSeconds * 1000;  
  18.             if (scheduleInterval < 0) {  
  19.                 scheduleInterval += new TimeSpan(24, 0, 0).TotalSeconds * 1000;  
  20.             }  
  21.             timer.Interval = scheduleInterval;  
  22.             timer.Enabled = true;  
  23.         }  
  24.         protected override void OnStop() {  
  25.             WriteLogFile("Service is stopped");  
  26.         }  
  27.         private void OnElapsedTime(object source, ElapsedEventArgs e) {  
  28.             if (timer.Interval != 24 * 60 * 60 * 1000) {  
  29.                 timer.Interval = 24 * 60 * 60 * 1000; //Reset the timer    
  30.             }  
  31.             string ApiData = new WebClient().DownloadString("http://localhost/WebApi/Api/values");  
  32.             WriteLogFile($ "Web Api called : Api Data {ApiData} ");  
  33.         }  
  34.         public void WriteLogFile(string message) {  
  35.             StreamWriter sw = null;  
  36.             sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt"true);  
  37.             sw.WriteLine($ "{DateTime.Now.ToString()} : {message}");  
  38.             sw.Flush();  
  39.             sw.Close();  
  40.         }  
  41.     }  
  42. }  
When we complete this step, we are now ready to build and install our service.
 
Build the windows service:
 
 
Open Command Prompt and Run as Administrator.
 
 
We will need to copy the path where our windows service is located and paste this in the command prompt.
 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe YourWindowsServiceLocation \WindowsApiCallService.exe
 
Upon successful installation, we can see our service installed as depicted here
 
 
We can now right-click and start our project.
 
When we open our windows service location, we can see our log file and see the entries according to our specified schedule.
 
 
Here are the links for the 2 projects we have worked on.
 
Web API Demo code: Web API.
 
Windows Scheduler demo code: Windows Scheduler.
 
Thanks!


Similar Articles