Implement job scheduler #6

Closed
opened 2026-10-04 19:27:59 +00:00 by daniel · 1 comment
Owner

Imported from GitHub samson-media/barn#6 — opened by @daniel-samson on 2026-01-21 12:36:35 UTC

Overview

Implement the job scheduler that manages concurrent job execution.

Context

  • Read first: docs/config.md (max_concurrent_jobs)
  • Depends on: #5 (process execution), #4 (job model)

Requirements

1. Scheduler Core

com.samsonmedia.barn.execution.JobScheduler.java:

public class JobScheduler {
    private final JobRepository repository;
    private final JobRunner runner;
    private final Config config;
    private final ExecutorService executor;
    
    // Start the scheduler
    public void start();
    
    // Stop gracefully (wait for running jobs)
    public void stop();
    
    // Stop immediately (kill running jobs)
    public void stopNow();
    
    // Submit a new job for execution
    public void submit(Job job);
    
    // Get scheduler status
    public SchedulerStatus getStatus();
}

public record SchedulerStatus(
    int runningJobs,
    int queuedJobs,
    int maxConcurrentJobs,
    boolean isRunning
) { }

2. Scheduling Algorithm

  • FIFO queue for jobs
  • Respect max_concurrent_jobs limit
  • Poll filesystem for queued jobs on startup
  • Handle job completion to free slots
// Scheduling loop (runs in background thread)
while (running) {
    if (runningCount < maxConcurrent) {
        Optional<Job> next = repository.findNextQueued();
        if (next.isPresent()) {
            executor.submit(() -> runner.run(next.get()));
            runningCount.incrementAndGet();
        }
    }
    Thread.sleep(pollInterval);
}

3. Scheduler Lock

Only one scheduler instance should run. Use lock file:

/tmp/barn/locks/scheduler.lock
public class SchedulerLock {
    public static Optional<SchedulerLock> tryAcquire(Path lockDir);
    public void release();
}

4. Job Priority (Optional)

Jobs can specify priority via tag or future field:

  • Higher priority jobs run first
  • Equal priority uses FIFO

5. Tests Required

  • JobSchedulerTest.java: Test start/stop, concurrent limits, FIFO order
  • SchedulerLockTest.java: Test lock acquisition, prevent double-start

Acceptance Criteria

  • Scheduler respects max_concurrent_jobs
  • Jobs execute in FIFO order
  • Only one scheduler can run (lock file)
  • Graceful shutdown waits for running jobs
  • Immediate shutdown kills running jobs
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Use ExecutorService with fixed thread pool:

ExecutorService executor = Executors.newFixedThreadPool(maxConcurrentJobs);

For graceful shutdown:

executor.shutdown();
if (!executor.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) {
    executor.shutdownNow();
}

Definition of Done

  • Scheduler manages concurrent execution
  • Lock prevents multiple schedulers
  • Start/stop work correctly
  • All tests pass
<!-- github-import:issue:6 --> _Imported from GitHub samson-media/barn#6 — opened by **@daniel-samson** on 2026-01-21 12:36:35 UTC_ ## Overview Implement the job scheduler that manages concurrent job execution. ## Context - **Read first**: `docs/config.md` (max_concurrent_jobs) - **Depends on**: #5 (process execution), #4 (job model) ## Requirements ### 1. Scheduler Core `com.samsonmedia.barn.execution.JobScheduler.java`: ```java public class JobScheduler { private final JobRepository repository; private final JobRunner runner; private final Config config; private final ExecutorService executor; // Start the scheduler public void start(); // Stop gracefully (wait for running jobs) public void stop(); // Stop immediately (kill running jobs) public void stopNow(); // Submit a new job for execution public void submit(Job job); // Get scheduler status public SchedulerStatus getStatus(); } public record SchedulerStatus( int runningJobs, int queuedJobs, int maxConcurrentJobs, boolean isRunning ) { } ``` ### 2. Scheduling Algorithm - FIFO queue for jobs - Respect `max_concurrent_jobs` limit - Poll filesystem for queued jobs on startup - Handle job completion to free slots ```java // Scheduling loop (runs in background thread) while (running) { if (runningCount < maxConcurrent) { Optional<Job> next = repository.findNextQueued(); if (next.isPresent()) { executor.submit(() -> runner.run(next.get())); runningCount.incrementAndGet(); } } Thread.sleep(pollInterval); } ``` ### 3. Scheduler Lock Only one scheduler instance should run. Use lock file: ``` /tmp/barn/locks/scheduler.lock ``` ```java public class SchedulerLock { public static Optional<SchedulerLock> tryAcquire(Path lockDir); public void release(); } ``` ### 4. Job Priority (Optional) Jobs can specify priority via tag or future field: - Higher priority jobs run first - Equal priority uses FIFO ### 5. Tests Required - `JobSchedulerTest.java`: Test start/stop, concurrent limits, FIFO order - `SchedulerLockTest.java`: Test lock acquisition, prevent double-start ## Acceptance Criteria - [ ] Scheduler respects max_concurrent_jobs - [ ] Jobs execute in FIFO order - [ ] Only one scheduler can run (lock file) - [ ] Graceful shutdown waits for running jobs - [ ] Immediate shutdown kills running jobs - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Use `ExecutorService` with fixed thread pool: ```java ExecutorService executor = Executors.newFixedThreadPool(maxConcurrentJobs); ``` For graceful shutdown: ```java executor.shutdown(); if (!executor.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) { executor.shutdownNow(); } ``` ## Definition of Done - Scheduler manages concurrent execution - Lock prevents multiple schedulers - Start/stop work correctly - All tests pass
daniel added this to the M2: Job Execution milestone 2026-10-04 19:27:59 +00:00
daniel added the execution label 2026-10-04 19:27:59 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 13:26:14 UTC:

✅ Ticket #6 completed: Implemented job scheduler with:

SchedulerLock (src/main/java/com/samsonmedia/barn/execution/SchedulerLock.java):

  • File-based locking using FileChannel.tryLock()
  • Ensures only one scheduler instance runs at a time
  • Handles both cross-process and same-JVM contention

JobScheduler (src/main/java/com/samsonmedia/barn/execution/JobScheduler.java):

  • Concurrent job execution with configurable max concurrent jobs
  • FIFO ordering based on job creation time
  • Respects retry delay (retryAt) for failed jobs
  • Graceful and immediate shutdown options
  • Status reporting (running jobs, queued jobs, max concurrent)

Tests:

  • SchedulerLockTest: 7 tests for lock acquisition, release, contention
  • JobSchedulerTest: 15 tests for start/stop, job execution, status, constructor validation

All 381 tests passing. mvn verify successful.

<!-- github-import:comment:3778131735 --> _**@daniel-samson** commented on 2026-01-21 13:26:14 UTC:_ ✅ Ticket #6 completed: Implemented job scheduler with: **SchedulerLock** (src/main/java/com/samsonmedia/barn/execution/SchedulerLock.java): - File-based locking using FileChannel.tryLock() - Ensures only one scheduler instance runs at a time - Handles both cross-process and same-JVM contention **JobScheduler** (src/main/java/com/samsonmedia/barn/execution/JobScheduler.java): - Concurrent job execution with configurable max concurrent jobs - FIFO ordering based on job creation time - Respects retry delay (retryAt) for failed jobs - Graceful and immediate shutdown options - Status reporting (running jobs, queued jobs, max concurrent) **Tests**: - SchedulerLockTest: 7 tests for lock acquisition, release, contention - JobSchedulerTest: 15 tests for start/stop, job execution, status, constructor validation All 381 tests passing. mvn verify successful.
This repo is archived. You cannot comment on issues.