Hello every I have faced an issue, I have created a background service in c# it's working but this service call when we start our project, But I want to call this service after running my server(Project) 10 min.
Loading
Hello every I have faced an issue, I have created a background service in c# it's working but this service call when we start our project, But I want to call this service after running my server(Project) 10 min.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh KumarRank #91 · 22.9K reputationPosted Apr 23, 2024, 3:14 AM EDT
Hello Sunny,
Please refer this thread,
https://www.c-sharpcorner.com/blogs/explain-background-service-in-c-sharp
Jignesh KumarRank #91 · 22.9K reputationPosted Apr 22, 2024, 2:26 AM EDT
Hello Sunny,
You can use in this way,
public class BackgroundService : BackgroundService { private readonly string _dbUserConn; private Timer _timer; public BackgroundService(string dbConn, string dbUserConn, IConfiguration configuration) { _dbUserConn = dbUserConn; _dbConn = dbConn; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { // Set 10 min times using below code _timer = new Timer(async _ => { await UpdateAccessTokenAsyncTask(); }, null, TimeSpan.Zero, TimeSpan.FromMinutes(10)); stoppingToken.Register(() => _timer.Dispose()); return Task.CompletedTask; } private async Task UpdateAccessTokenAsyncTask() { using (SqlConnection cnn = new SqlConnection(_dbUserConn)) { try { var getUserWithGoogleAuthDetails = await cnn.QueryAsync("exec sp"); foreach (var user in getUserWithGoogleAuthDetails) { if (user != null && user.tokenExpiryDateTime < DateTime.UtcNow) { //your require logic you can add here } } } catch (Exception ex) { // Log the exception for your service here Console.WriteLine($"Error in UpdateAccessTokenAsyncTask: {ex.Message}"); } } } // Other methods if you require additional method to executes }Sourabh DhimanRank #2,987 · 483 reputationPosted Apr 22, 2024, 1:53 AM EDT
public class BackgroundService : BackgroundService { private readonly string _dbUserConn; public BackgroundService(string dbConn, string dbUserConn, IConfiguration configuration) { _httpClient = new HttpClient(); _configuration = configuration; _dbUserConn = dbUserConn; _dbConn = dbConn; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { var timer = new Timer(async _ => { await UpdateAccessTokenAsyncTask(); }, null, TimeSpan.Zero, TimeSpan.FromMinutes(2)); stoppingToken.Register(() => timer.Dispose()); return Task.CompletedTask; } private async Task UpdateAccessTokenAsyncTask() { using (SqlConnection cnn = new SqlConnection(_dbUserConn)) { try { var getUserWithGoogleAuthDetails = await cnn.QueryAsync("exec sp"); foreach (var user in getUserWithGoogleAuthDetails) { if (user != null && user.tokenExpiryDateTime GetRefreshAccessTokenAsync(string refreshToken, string clientId, string clientSecret) { try { //code } catch (Exception ex) { Console.WriteLine($"Error refreshing access token: {ex.Message}"); throw; } throw new InvalidOperationException("Access token not found in the response."); } }This is my code and I have registered this service in startup.cs file
Sourabh DhimanRank #2,987 · 483 reputationPosted Apr 22, 2024, 2:55 AM EDT
Jignesh it is not working, I started my project it's service run. Please check this startup.cs file code
(provider =>()));
services.AddHostedService
new CommonBackgroundService(dbConn,dbUserConn, provider.GetRequiredService
Kiran GiraseRank #3,637 · 402 reputationPosted Apr 23, 2024, 4:37 AM EDT
Hi Sunny,
To delay the start of your background service in C# after running your server (project), you can utilize a timer or a delayed task to achieve this. Here's a basic outline of how you can implement it:
1.Create a Timer: You can use a timer to wait for 10 minutes after your server (project) starts.
2.Start the Background Service: Once the timer expires, start your background service.
using System; using System.Threading; public class YourServer { private BackgroundService backgroundService; public YourServer() { // Initialize your server // ... // Start a timer after server starts Timer timer = new Timer(StartBackgroundService, null, TimeSpan.FromMinutes(10), TimeSpan.Zero); } private void StartBackgroundService(object state) { // Initialize your background service backgroundService = new BackgroundService(); // Start your background service backgroundService.Start(); // Dispose the timer as it's no longer needed ((Timer)state).Dispose(); } } public class BackgroundService { public void Start() { // Start your background service logic // ... Console.WriteLine("Background service started."); } }In this example:
YourServerclass represents your server (project).YourServeris created, it starts a timer with an initial delay of 10 minutes (TimeSpan.FromMinutes(10)).StartBackgroundServicemethod is called, which initializes and starts your background service.Abhishek YadavRank #217 · 11.3K reputationPosted Apr 24, 2024, 6:13 AM EDT
services.AddHostedService(provider => { Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith(_ => { return new CommonBackgroundService(dbConn, dbUserConn, provider.GetRequiredService()); }); });try this in startup.cs