I have a .NET 8 application which, among other things, has the following functionality: it contains a hosted service that fetches some records from a database, produces some .txt
files and writes them on the path /mnt/import
. The background service must run on a specified interval.
The code for the background service look like this
using Microsoft.Extensions.Hosting;
namespace ArrivalConfirmation.ExporterService.Shared.Hosting.Abstractions;
public class ScheduledBackgroundService(TimeSpan period) : BackgroundService
{
private readonly PeriodicTimer _timer = new(period);
public TimeSpan Period { get; } = period;
/// <summary>Contains the logic that runs at the specified time interval.</summary>
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>
private ValueTask RunLoopAsync(CancellationToken stoppingToken)
{
/* Other code removed for brevity. */
await File.WriteAllTextAsync(path, content);
}
/// <summary>Calls the <see cref="RunLoopAsync(CancellationToken)"/> method at the specified time interval.</summary>
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
protected override sealed async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested && await _timer.WaitForNextTickAsync(stoppingToken)) {
await RunLoopAsync(stoppingToken);
}
}
/// <inheritdoc />
public override void Dispose() {
_timer.Dispose();
base.Dispose();
}
}
The weird thing is that when this code runs it works as expected locally, but when deployed to production, the files are written, but are lost after a short period of time.
The application runs on Azure Kuberneres Service and when deployed a docker image is used. This image is nothing special, it is just the image created from the default Dockerfile provided by Visual Studio.
On the aforementioned path, a persistent volume is mounted. I have tried to write files from the command line in k8s and the files remain after pod up or down. The even more strange thing is that when I tried to write files outside the scope of the background service the files also stay and not deleted. But when the same code runs inside a background service the files are deleted automatically after some seconds.
Does anyone have any clue what can cause this behavior? Thanks in advance.
3