5
Answers

make background service run in iis even if iis is idle

Photo of kaushik guru

kaushik guru

1y
609
1

i am implementing a background service , the problem is when i run it in local it is working fine since the app is hit and running . but in iis i deployed code and started the server in iis. the background service is not running until i browse the site and becoming idle when the server is idle

using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using handbook.Controllers.HR;
using handbook.Data;
using handbook.Models.Mail;
using handbook.Repositories.Implementation;
using handbook.Repositories.Interface;
using handbook.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Globalization;
using System.Linq;

namespace handbook.BackgroundmailService
{
    public class EmailReminderSenderService : IHostedService, IDisposable
    {
        public static IConfiguration Configuration { get; set; }
        private Timer _timer;
        private readonly IOauthMailService _emailSender;
        private readonly ILogger<EmailReminderSenderService> _logger;

        public EmailReminderSenderService(IOauthMailService emailSender, ILogger<EmailReminderSenderService> logger, IServiceProvider serviceProvider, IConfiguration configuration)
        {
            _emailSender = emailSender;
            _logger = logger;
            Services = serviceProvider;
            Configuration = configuration;
        }

        public IServiceProvider Services { get; }

        private static TimeSpan getJobRunDelay()
        {
            // Change the delay to run every 10 minutes
            return TimeSpan.FromMinutes(1);
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background service is started");
            _timer = new Timer(SendEmails, null, getJobRunDelay(), getJobRunDelay());
            return Task.CompletedTask;
        }
public async void SendEmails(object state)
        {
my task
}
public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background service is stopping");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }
    }
}
C#

My program. cs

builder.Services.AddHostedService<FailedEmailManagmentService>();
C#

i have registered it also 

Answers (5)

0
Photo of El Mahdi Archane
NA 6.7k 4.6m 7y
Hi Akshaya,
 
If you are using @Ajax.ActionLink() Helper. This article describes deeply how you can use @Ajax.ActionLink. 
 
Link
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/.
 
If you are working with jQeury Ajax method. I think that the responses which are shared below will help you to solve your issue.
 
 
0
Photo of Dharmraj Thakur
249 7.7k 718.3k 7y
Hi Akshaya,
 
follow this...
 
  1. var postData = {  
  2.     "ID": $("#ID").val(),  
  3.     "Name": $("#Name").val(),  
  4.     "Remarks": $("#Remarks").val()  
  5. };  
  6. $.ajax({  
  7.     url: "/Controller/Action",  
  8.     type: 'POST',  
  9.     data: JSON.stringify(postData),  
  10.     contentType: "application/json",  
  11.     dataType: 'json',  
  12.     async: true,  
  13.     success: function (res) {  
  14.         console.log(JSON.stringify(res, null, 5));  
  15.         if (parseInt(res["ResponseData"]["InsertedID"]) > 0) //here is how to get response from controller  
  16.         {  
  17.             alert("Updated successfully");  
  18.         }  
  19.     },  
  20.     error: function () {  
  21.         alert("Error");  
  22.         console.log(JSON.stringify(res, null, 5));  
  23.     },  
  24. }); 
 
0
Photo of Ramesh Palanivel
203 9.6k 1.5m 7y
Hi akshaya,
  
You can pass through via, "data" option in your ajax method,
 
Please find the sample code here,
  1. $.ajax({  
  2. type: "POST",  
  3. url: "/JQueryAjaxCall/AjaxPostCall",  
  4. data: {Id:$('#EmpId).val(),Name:$('#Empname').val()},  
  5. contentType: "application/json; charset=utf-8",  
  6. dataType: "json",  
  7. success: function(response) {  
  8. if (response != null) {  
  9. alert("Name : " + response.Name + ", Designation : " + response.Designation + ", Location :" + response.Location);  
  10. else {  
  11. alert("Something went wrong");  
  12. }  
  13. },  
  14. failure: function(response) {  
  15. alert(response.responseText);  
  16. },  
  17. error: function(response) {  
  18. alert(response.responseText);  
  19. }  
  20. });  
-1
Photo of Gohil Jayendrasinh
NA 5.1k 3.7m 7y
var objPostedData = new Object();
objPostedData["ID"] = $("#ID").val();
objPostedData["Name"] = $("#Name").val();
objPostedData["Remarks"] = $("#Remarks").val();
/*
-- For Passing Array Object
var PostedDataArray = new Array();
PostedData[0] = objPostedData ;
*/
var objurl = "/Controller/Action";
var objdata = "{ 'jsonstring': '" + JSON.stringify(objPostedData ) + "'}";
$.ajax({
type: "POST",
url: objurl,
data: objdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
ShowSuccess("Call is successfully escalated.");
},
error: function (msg) {
alert(msg);
}
});
/*.cs file*/
[HttpPost]
public ActionResult CallEscalation(string jsonstring)
{
DatabaseRepository dr = new DatabaseRepository();
DataTable dt = new DataTable();
var data = new JavaScriptSerializer().Deserialize<PostedData>(jsonstring);
//var list = new JavaScriptSerializer().Deserialize<List<PostedData>>(jsonstring); // For List
}
calss PostedData
{
private string _ID;
public string ID
{
get { return _ID; }
set { rolename = value; }
}
private string _Name;
public string Name
{
get { return _Name; }
set { rolename = value; }
}
private string _Remarks;
public string Remarks
{
get { return _Remarks; }
set { rolename = value; }
}
}