🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / .Net Core Web Api / BackgroundService ile timer kullanımı

1-) .Net Core Web Api  - BackgroundService ile timer kullanımı

 

Not : .net core 8 olarak projeyi oluştur. sonra 9 veya 10 a yükselt.

her 10 saniyede bir images klasörü yoksa oluşturur varsa içine yyyy.MM.dd.HH.mm.ss.txt diye kayıtlar atar. çalıştığını buradan anlarsın

 

1. FileWriterService.cs

 

namespace TestApi

{

    public class FileWriterService : BackgroundService

    {

        private readonly string _basePath;

        private readonly int _intervalSeconds=10;

 

        public FileWriterService(IWebHostEnvironment env, IConfiguration config)

        {

            _basePath = Path.Combine(env.ContentRootPath, "images");

        }

 

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)

        {

            Directory.CreateDirectory(_basePath);

 

            while (!stoppingToken.IsCancellationRequested)

            {

                string fileName = DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss") + ".txt";

                string filePath = Path.Combine(_basePath, fileName);

 

                await File.WriteAllTextAsync(filePath, $"Çalışıyor: {DateTime.Now:O}", stoppingToken);

 

                await Task.Delay(TimeSpan.FromSeconds(_intervalSeconds), stoppingToken);

            }

        }

    }

}

 

 

 

 

 

2. program.cs

 

 

builder.Services.AddHostedService<FileWriterService>();

 

var app = builder.Build();

 

 

 

aşağıdaki son 5 dosya hariç siler

 

namespace TestApi

{

    public class FileWriterService : BackgroundService

    {

        private readonly string _basePath;

        private readonly int _intervalSeconds = 5;

        private readonly int _maxFiles = 5;

 

        public FileWriterService(IWebHostEnvironment env, IConfiguration config)

        {

            _basePath = Path.Combine(env.ContentRootPath, "images");

        }

 

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)

        {

            Directory.CreateDirectory(_basePath);

 

            while (!stoppingToken.IsCancellationRequested)

            {

                string fileName = DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss") + ".txt";

                string filePath = Path.Combine(_basePath, fileName);

 

                await File.WriteAllTextAsync(filePath, $"Çalışıyor: {DateTime.Now:O}", stoppingToken);

 

                // Fazla dosyaları sil

                CleanupOldFiles();

 

                await Task.Delay(TimeSpan.FromSeconds(_intervalSeconds), stoppingToken);

            }

        }

 

        private void CleanupOldFiles()

        {

            try

            {

                var files = new DirectoryInfo(_basePath)

                    .GetFiles("*.txt")

                    .OrderByDescending(f => f.CreationTimeUtc)

                    .ToList();

 

                if (files.Count > _maxFiles)

                {

                    var filesToDelete = files.Skip(_maxFiles);

                    foreach (var file in filesToDelete)

                    {

                        try

                        {

                            file.Delete();

                        }

                        catch

                        {

                            // Silme hatasını yut (dosya başka bir işlem tarafından kullanılıyor olabilir)

                        }

                    }

                }

            }

            catch

            {

                // Klasör erişim hatalarını görmezden gel

            }

        }

    }

}

 

 

 

 

tüm program.cs

 

 

using Microsoft.Extensions.FileProviders;

using TestApi;

 

var builder = WebApplication.CreateBuilder(args);

 

// Add services to the container.

 

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

 

builder.Services.AddHostedService<FileWriterService>();

 

var app = builder.Build();

 

 

 

var imagesFolder = Path.Combine(Directory.GetCurrentDirectory(), "images");

 

if (!Directory.Exists(imagesFolder))

{

    Directory.CreateDirectory(imagesFolder);

}

 

var fileProvider = new PhysicalFileProvider(

    Path.Combine(Directory.GetCurrentDirectory(), "images"));

 

var options = new FileServerOptions

{

    FileProvider = fileProvider,

    RequestPath = "/images",

    EnableDirectoryBrowsing = true

};

 

app.UseFileServer(options);

 

app.UseCors(builder => builder

.AllowAnyHeader()

.AllowAnyMethod()

.AllowAnyOrigin()

);

 

if (app.Environment.IsDevelopment() || app.Environment.IsProduction())

{

    app.UseDeveloperExceptionPage();

    app.UseSwagger();

    app.UseSwaggerUI(c => {

        c.SwaggerEndpoint("/swagger/v1/swagger.json", "myapi v1");

    });

}

 

app.UseHttpsRedirection();

 

app.UseAuthorization();

 

app.MapControllers();

 

app.Run();

 

 

 

 2025 Temmuz 31 Perşembe
 56