#BackgroundService
Explore tagged Tumblr posts
kidshandprint · 10 days ago
Text
Tumblr media
This battery monitoring application provides real-time tracking of your device's battery level, voltage, temperature, and charging status with automatic data collection every few seconds. It features interactive charts with zoom and pan capabilities that visualize battery performance over time, allowing you to switch between battery level, voltage, and temperature views. The app stores all battery data persistently in a local database, enabling historical analysis and tracking of charging cycles, consumption rates, and battery health trends. It includes diagnostic tools for testing charging and discharge rates, along with detailed statistics about your battery usage patterns and performance metrics. The application runs a background monitoring service to continuously collect data even when not actively using the app, and provides export functionality for sharing or backing up your battery data.
0 notes
erossiniuk · 4 years ago
Text
Managing a .NET Service with Blazor
In this post I will show you how creating a cross-platform and managing a .NET Service with Blazor that can be installed on Windows (Service) and Linux (systemd).
There is a lot of information on how to run a .NET project as a service, on Windows and on Linux (Mac is not supported yet). I will provide a sample project on GitHub and will only show some of the basics here.
The most interesting part for me is hosting a Blazor Server application with Kestrel as a service on both Windows and Linux. This gives endless possibilities in managing the service, not even from the system itself but also remotely.
Managing service with Blazor
First we create a normal Blazor Server project. I keep the project as-is and just add a few classes to demonstrate the use of Blazor in the service.
Adding the background service
Create a class called CustomBackgroundService. I use the BackgroundService as a base class but I could also implement IHostedService. More information about the different types can be found here.
This service is just logging and then waiting for 5 seconds to simulate a process that runs for a while:
public class CustomBackgroundService : BackgroundService { public bool IsRunning { get; set; } private readonly ILogger<CustomBackgroundService> _logger; public CustomBackgroundService(ILogger<CustomBackgroundService> logger) => _logger = logger; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { _logger.LogInformation($"{nameof(CustomBackgroundService)} starting {nameof(ExecuteAsync)}"); IsRunning = true; while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation($"{nameof(CustomBackgroundService)} running {nameof(ExecuteAsync)}"); await Task.Delay(5000); } IsRunning = false; _logger.LogInformation($"{nameof(CustomBackgroundService)} ending {nameof(ExecuteAsync)}"); } catch (Exception exception) { _logger.LogError(exception.Message, exception); } finally { IsRunning = false; } } }
Registering and adding the hosted service:
services .AddLogging(logging => logging.AddConsole()) .AddSingleton<WeatherForecastService>() .AddSingleton<CustomBackgroundService>() .AddHostedService(serviceCollection => serviceCollection.GetRequiredService<CustomBackgroundService>());
I added a new Razor page and added it to the menu (Pages/Service.razor):
@page "/Service" @inject CustomBackgroundService _customBackgroundService <h3>Service</h3> <p><div hidden="@HideIsRunning">Running</div></p> <button name="startButton" class="btn btn-primary" @onclick="Start">Start</button> <button class="btn btn-primary" @onclick="Stop">Stop</button> @code { private bool _isRunning { get; set; } public bool HideIsRunning => !_isRunning; protected override void OnInitialized() { _isRunning = _customBackgroundService.IsRunning; base.OnInitialized(); } private async Task Start() { if(!_customBackgroundService.IsRunning) await _customBackgroundService.StartAsync(new System.Threading.CancellationToken()); _isRunning = _customBackgroundService.IsRunning; } private async Task Stop() { if(_customBackgroundService.IsRunning) await _customBackgroundService.StopAsync(new System.Threading.CancellationToken()); _isRunning = _customBackgroundService.IsRunning; } }
Adding a new menu item to the default Blazor application by changing `Shared/NavMenu.razor’:
<div class="nav-item px-3"> <NavLink class="nav-link" href="Service"> <span class="oi oi-pulse" aria-hidden="true"></span> Service </NavLink> </div>
When debugging the project this should be visible:
Tumblr media
Blazor with running service
you can start and stop the service and check the console of your IDE to see the output:
Tumblr media
Output from the service
Running and installing the service
To run the application as a Service the following code has to be added to the Program.cs:
public static void Main(string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) Directory.SetCurrentDirectory(Environment.ProcessPath!); var builder = CreateHostBuilder(args.Where(arg => arg != "--console").ToArray()); if (isService) { if (OperatingSystem.IsWindows()) builder.UseWindowsService(); else if (OperatingSystem.IsLinux()) builder.UseSystemd(); else throw new InvalidOperationException( $"Can not run this application as a service on this Operating System"); } builder.Build().Run(); }
Next, install the following Nuget packages:
Windows: Microsoft.Extensions.Hosting.WindowsServices
Linux: Microsoft.Extensions.Hosting.Systemd
.NET Service on Windows
First, publish the application to a folder. Make sure to create the correct publish profile for Windows. Also, consider if you need to publish it Framework-Dependent (the .NET framework has to be installed on the host machine) or Self-Contained (everything needed is included, how cool is that!):
Tumblr media
.NET Launch Settings Profile
After publishing, open a Powershell command line, go to the directory conaining the newly published service and execute the following commands:
New-Service -Name “Blazor Background Service” -BinaryPath .\BlazorBackgroundservice.BlazorUI.exe
Tumblr media
PowerShell registers the Blazor service
Start-Service -Name “BlazorBackgroundService”
Tumblr media
PowerShell starts the new service
I could write logs to the Event Logger but I decided to write simple logs to a text file. When you look into the directory of the service you should see a logfile log****.txt. Look into the logfile to see if the service is running. When going to the url’s provided in the logfile be aware that the https port might not work because there are no valid SSL certificates installed.
Tumblr media
Logging on Windows
.NET Service on Linux
Same as for Windows: publish the application to a folder, using the correct publish configuration. I can test the application by adding --console to the command line:
Tumblr media
Running on Arch Linux
To install it as a service I created the file in/etc/systemd/system/blazorbackgroundservice.service:
[Unit] Description=Blazor Background Service [Service] Type=Notify ExecStart=/home/jacob/blazorbackgroundservice/linux/BlazorBackgroundService.BlazorUI [Install] WantedBy=multi-user.target
Run the following commands:
sudo systemctl daemon-reload sudo systemctl status blazorbackgroundservice
Tumblr media
Stopped service
sudo systemctl start blazorbackgroundservice sudo systemctl status blazorbackgroundservice
Tumblr media
It works! Check the status output for the url of the Blazor website and browse to the site to check if it works.
You can even auto-start the service by running the following command:
sudo systemctl enable blazorbackgroundservice
Next time you reboot, the service will automatically start.
Resources
Microsoft.Extensions.Hosting.WindowsServices
Microsoft.Extensions.Hosting.Systemd
Background tasks with hosted services in ASP.NET Core
The post Managing a .NET Service with Blazor appeared first on PureSourceCode.
from WordPress https://www.puresourcecode.com/dotnet/blazor/managing-a-net-service-with-blazor/
0 notes
clippingpathexpertsusa · 7 years ago
Photo
Tumblr media
One of the most popular services we offer here at Graphic Experts Ltd is the, #BackgroundService, #AutomotiveCarInventory, #PhotoBackgrounding, #cardesign, #careditingphotoshop, #vehiclephotoshop. More info click here. https://bit.ly/2usggjf — view on Instagram https://ift.tt/2JOXHL2
1 note · View note
philipholt · 6 years ago
Text
dotnet new worker - Windows Services or Linux systemd services in .NET Core
You've long been able to write Windows Services in .NET and .NET Core, and you could certainly write a vanilla Console App and cobble something together for a long running headless service as well. However, the idea of a Worker Process, especially a long running one is a core part of any operating system - Windows, Linux, or Mac.
Now that open source .NET Core is cross-platform, it's more than reasonable to want to write OS services in .NET Core. You might write a Windows Service with .NET Core or a systemd process for Linux with it as well.
Go grab a copy of .NET Core 3.0 - as of the time of this writing it's very close to release, and Preview 8 is supported in Production.
If you're making a Windows Service, you can use the Microsoft.Extensions.Hosting.WindowsService package and tell your new Worker that its lifetime is based on ServiceBase.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices(services => { services.AddHostedService<Worker>(); });
If you're making a Linux worker and using systemd you'd add the Microsoft.Extensions.Hosting.Systemd package and tell your new Worker that its lifetime is managed by systemd!
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSystemd() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });
The Worker template in .NET Core makes all this super easy and familiar if you're used to using .NET already. For example, logging is built in and regular .NET log levels like LogLevel.Debug or LogLevel.Critical are automatically mapped to systemd levels like Debug and Crit so I could run something like sudo journalctl -p 3 -u testapp and see my app's logs, just alike any other Linux process because it is!
You'll notice that a Worker doesn't look like a Console App. It has a Main but your work is done in a Worker class. A hosted service or services is added with AddHostedService and then a lot of work is abstracted away from you. The Worker template and BackgroundService base class brings a lot of the useful conveniences you're used to from ASP.NET over to your Worker Service. You get dependency injection, logging, process lifetime management as seen above, etc, for free!
public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } }
This is a very useful template and it's available from the command line as "dotnet new worker" or from File New Project in Visual Studio 2019 Preview channel.
Also check out Brady Gaster's excellent blog post on running .NET Core workers in containers in Azure Container Instances (ACI). This is super useful if you have some .NET Core and you want to Do A Thing in the cloud but you also want per-second billing for your container.
Sponsor: Get the latest JetBrains Rider with WinForms designer, Edit & Continue, and an IL (Intermediate Language) viewer. Preliminary C# 8.0 support, rename refactoring for F#-defined symbols across your entire solution, and Custom Themes are all included.
© 2019 Scott Hanselman. All rights reserved.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
      dotnet new worker - Windows Services or Linux systemd services in .NET Core published first on http://7elementswd.tumblr.com/
0 notes
suzanneshannon · 6 years ago
Text
dotnet new worker - Windows Services or Linux systemd services in .NET Core
You've long been able to write Windows Services in .NET and .NET Core, and you could certainly write a vanilla Console App and cobble something together for a long running headless service as well. However, the idea of a Worker Process, especially a long running one is a core part of any operating system - Windows, Linux, or Mac.
Now that open source .NET Core is cross-platform, it's more than reasonable to want to write OS services in .NET Core. You might write a Windows Service with .NET Core or a systemd process for Linux with it as well.
Go grab a copy of .NET Core 3.0 - as of the time of this writing it's very close to release, and Preview 8 is supported in Production.
If you're making a Windows Service, you can use the Microsoft.Extensions.Hosting.WindowsService package and tell your new Worker that its lifetime is based on ServiceBase.
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices(services => { services.AddHostedService<Worker>(); });
If you're making a Linux worker and using systemd you'd add the Microsoft.Extensions.Hosting.Systemd package and tell your new Worker that its lifetime is managed by systemd!
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSystemd() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });
The Worker template in .NET Core makes all this super easy and familiar if you're used to using .NET already. For example, logging is built in and regular .NET log levels like LogLevel.Debug or LogLevel.Critical are automatically mapped to systemd levels like Debug and Crit so I could run something like sudo journalctl -p 3 -u testapp and see my app's logs, just alike any other Linux process because it is!
You'll notice that a Worker doesn't look like a Console App. It has a Main but your work is done in a Worker class. A hosted service or services is added with AddHostedService and then a lot of work is abstracted away from you. The Worker template and BackgroundService base class brings a lot of the useful conveniences you're used to from ASP.NET over to your Worker Service. You get dependency injection, logging, process lifetime management as seen above, etc, for free!
public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } }
This is a very useful template and it's available from the command line as "dotnet new worker" or from File New Project in Visual Studio 2019 Preview channel.
Also check out Brady Gaster's excellent blog post on running .NET Core workers in containers in Azure Container Instances (ACI). This is super useful if you have some .NET Core and you want to Do A Thing in the cloud but you also want per-second billing for your container.
Sponsor: Get the latest JetBrains Rider with WinForms designer, Edit & Continue, and an IL (Intermediate Language) viewer. Preliminary C# 8.0 support, rename refactoring for F#-defined symbols across your entire solution, and Custom Themes are all included.
© 2019 Scott Hanselman. All rights reserved.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
      dotnet new worker - Windows Services or Linux systemd services in .NET Core published first on https://deskbysnafu.tumblr.com/
0 notes
idanalytics · 5 years ago
Text
Background verification companies in Bangalore
Employment check has become more of a need in recent times. it is difficult for an HR of the company to perform due diligence on their own. Moreover, it requires an effective background verification process to identify and eliminate dishonest candidates. Whether a large or Small Business, hiring qualified and honest employees is important to the success of any company. Background checks companies can help you get them on the job quickly and easy to use employee background check process.
As a background verification agency, we have a dedicated team and excelled in background checks. you can screen your applicants for any background related issues. We do an array of verifications that are reported with evidence and bound by TAT. We provide real-time updates & download reports.
0 notes
alanlcole · 6 years ago
Text
Consuming RabbitMQ Messages In ASP.NET Core
In this article, I’d like to present how to consume the RabbitMQ message via BackgroundService in ASP.NET Core. source https://www.c-sharpcorner.com/article/consuming-rabbitmq-messages-in-asp-net-core/ from C Sharp Corner https://ift.tt/2SY0yLn
0 notes
carlajsmith · 6 years ago
Text
Consuming RabbitMQ Messages In ASP.NET Core
In this article, I’d like to present how to consume the RabbitMQ message via BackgroundService in ASP.NET Core. from C-Sharpcorner Latest Content https://ift.tt/2txtbj1
from C Sharp Corner https://csharpcorner.tumblr.com/post/182984256511
0 notes
csharpcorner · 6 years ago
Text
Consuming RabbitMQ Messages In ASP.NET Core
In this article, I’d like to present how to consume the RabbitMQ message via BackgroundService in ASP.NET Core. from C-Sharpcorner Latest Content https://ift.tt/2txtbj1
0 notes
just4programmers · 7 years ago
Text
ASP.NET Core Architect David Fowler's hidden gems in 2.1
Open source ASP.NET Core 2.1 is out, and Architect David Fowler took to twitter to share some hidden gems that not everyone knows about. Sure, it's faster, builds faster, runs faster, but there's a number of details and fun advanced techniques that are worth a closer look at.
.NET Generic Host
ASP.NET Core introduced a new hosting model. .NET apps configure and launch a host.
The host is responsible for app startup and lifetime management. The goal of the Generic Host is to decouple the HTTP pipeline from the Web Host API to enable a wider array of host scenarios. Messaging, background tasks, and other non-HTTP workloads based on the Generic Host benefit from cross-cutting capabilities, such as configuration, dependency injection (DI), and logging.
This means that there's not just a WebHost anymore, there's a Generic Host for non-web-hosting scenarios. You get the same feeling as with ASP.NET Core and all the cool features like DI, logging, and config. The sample code for a Generic Host is up on GitHub.
IHostedService
A way to run long running background operations in both the generic host and in your web hosted applications. ASP.NET Core 2.1 added support for a BackgroundService base class that makes it trivial to write a long running async loop. The sample code for a Hosted Service is also up on GitHub.
Check out a simple Timed Background Task:
public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Timed Background Service is starting."); _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask; }
Fun!
Windows Services on .NET Core
You can now host ASP.NET Core inside a Windows Service! Lots of people have been asking for this. Again, no need for IIS, and you can host whatever makes you happy. Check out Microsoft.AspNetCore.Hosting.WindowsServices on NuGet and extensive docs on how to host your own ASP.NET Core app without IIS on Windows as a Windows Service.
public static void Main(string[] args) { var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); var host = WebHost.CreateDefaultBuilder(args) .UseContentRoot(pathToContentRoot) .UseStartup<Startup>() .Build(); host.RunAsService(); }
IHostingStartup - Configure IWebHostBuilder with an Assembly Attribute
Simple and clean with source on GitHub as always.
[assembly: HostingStartup(typeof(SampleStartups.StartupInjection))]
Shared Source Packages
This is an interesting one you should definitely take a moment and pay attention to. It's possible to build packages that are used as helpers to share source code. We internally call these "shared source packages." These are used all over ASP.NET Core for things that should be shared BUT shouldn't be public APIs. These get used but won't end up as actual dependencies of your resulting package.
They are consumed like this in a CSPROJ. Notice the PrivateAssets attribute.
<PackageReference Include="Microsoft.Extensions.ClosedGenericMatcher.Sources" PrivateAssets="All" Version="" /> <PackageReference Include="Microsoft.Extensions.ObjectMethodExecutor.Sources" PrivateAssets="All" Version="" />
ObjectMethodExecutor
If you ever need to invoke a method on a type via reflection and that method could be async, we have a helper that we use everywhere in the ASP.NET Core code base that is highly optimized and flexible called the ObjectMethodExecutor.
The team uses this code in MVC to invoke your controller methods. They use this code in SignalR to invoke your hub methods. It handles async and sync methods. It also handles custom awaitables and F# async workflows
SuppressStatusMessages
A small and commonly requested one. If you hate the output that dotnet run gives when you host a web application (printing out the binding information) you can use the new SuppressStatusMessages extension method.
WebHost.CreateDefaultBuilder(args) .SuppressStatusMessages(true) .UseStartup<Startup>();
AddOptions
They made it easier in 2.1 to configure options that require services. Previously, you would have had to create a type that derived from IConfigureOptions<TOptions>, now you can do it all in ConfigureServices via AddOptions<TOptions>
public void ConfigureServicdes(IServiceCollection services) { services.AddOptions<MyOptions>() .Configure<IHostingEnvironment>((o,env) => { o.Path = env.WebRootPath; }); }
IHttpContext via AddHttpContextAccessor
You likely shouldn't be digging around for IHttpContext, but lots of folks ask how to get to it and some feel it should be automatic. It's not registered by default since having it has a performance cost. However, in ASP.NET Core 2.1 a PR was put in for an extension method that makes it easy IF you want it.
services.AddHttpContextAccessor();
So ASP.NET Core 2.1 is out and ready to go. 
New features in this release include:
SignalR – Add real-time web capabilities to your ASP.NET Core apps.
Razor class libraries – Use Razor to build views and pages into reusable class libraries.
Identity UI library & scaffolding – Add identity to any app and customize it to meet your needs.
HTTPS – Enabled by default and easy to configure in production.
Template additions to help meet some GDPR requirements – Give users control over their personal data and handle cookie consent.
MVC functional test infrastructure – Write functional tests for your app in-memory.
[ApiController], ActionResult<T> – Build clean and descriptive web APIs.
IHttpClientFactory – HttpClient client as a service that you can centrally manage and configure.
Kestrel on Sockets – Managed sockets replace libuv as Kestrel's default transport.
Generic host builder – Generic host infrastructure decoupled from HTTP with support for DI, configuration, and logging.
Updated SPA templates – Angular, React, and React + Redux templates have been updated to use the standard project structures and build systems for each framework (Angular CLI and create-react-app).
Check out What's New in ASP.NET Core 2.1 in the ASP.NET Core docs to learn more about these features. For a complete list of all the changes in this release, see the release notes.
Go give it a try. Follow this QuickStart and you can have a basic Web App up in 10 minutes.
Sponsor: Check out JetBrains Rider: a cross-platform .NET IDE. Edit, refactor, test and debug ASP.NET, .NET Framework, .NET Core, Xamarin or Unity applications. Learn more and download a 30-day trial!
© 2018 Scott Hanselman. All rights reserved.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
0 notes
night-finance-site-blog · 8 years ago
Text
リトライ感覚通信
public class BackgroundService extends IntentService { private static final String TAG = "BackgroundService"; private static final String PREF_NAME = "com.example.backoffsample"; private static final String PREF_KEY_BACKOFF = "pref_key_backoff"; // public static final long INTIAL_BACKOFF_MS = 3 * 1000; public BackgroundSErvice"); } public static void setBackoff(Context context, long timeMs){ final SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putLong(PREF_KEY_BACKOFF, timeMs); editor.commit(); } public static long getBackoff(Context context){ final SharedPreferences(PREF_NAME, Context.MODE_PRIVATE); return prefs.getlong(PREF_KEY__BACKOFF, 0); } @Override protected void onHandleIntent(Intent intent) { Log.v(TAG, ""); // try{ Thread.sleep(3 * 1000); }catch((Exception e){ } Log.v(TAG, ""); // long nextInterval = getBackoff(this); // // if(nextInterval = getBackoff(this); // // if(nextInterval > 0){ Log.v(TAG, ":" + nextInterval); // PendingIntent pendingIntent = PendingIntent.getService(this, 0, new Intent(this,BackgroundService.class), PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextInterval, pendingIntent); // setBackoff(thid, nextInterval*2); }else{ Log.v(TAG, ""); } } }
<service android:name".BackgroundService" android:exported="false"></service>
0 notes
clippingpathexpertsusa · 7 years ago
Text
Auto mobile Car Inventory Backgrounding
Graphics Experts Ltd is the right solution for all of your graphic design needs. Graphics Experts Ltd is a graphic studio with its main office in UK and offices in Dhaka, Bangladesh. We offer affordable, professional services that encompass everything from #carinventory, #CarInventoryBackgroundService, #CarInventoryPhotoBackgrounding, #AutomotiveCarInventory, #BackgroundService, #AutomotiveCarInventory. More info click here.
https://bit.ly/2Ne3SdL
Tumblr media
0 notes