What Are Nightly Builds in Jenkins?

What Are Nightly Builds in Jenkins?

The scheduled, do-it-all build that runs while your team sleeps. Learn what a nightly build is, how to schedule it, what belongs inside it, how to protect your machines and your time, and how to turn every morning's result into useful action.

Imagine a bakery that closes at six in the evening. During the day, the bakers make small quick checks: is the oven hot, is the dough rising, does this loaf look right? Those checks are fast, because customers are waiting. But after closing, when the shop is quiet, a different routine begins. Every oven is tested. Every recipe is baked from scratch. Every ingredient delivery is inspected. It takes hours, but nobody is waiting, so the thoroughness costs no one any time. By morning, the owner has a full report on the health of the whole bakery.

A nightly build in Jenkins is that after-hours routine. While developers are away from their desks, Jenkins wakes up on a schedule and does the big, slow, thorough work that would be too heavy to run on every small change. It compiles everything from scratch, runs the complete set of tests, scans for problems, packages the result, and leaves a report waiting for the team’s first cup of coffee.

In this guide you will learn what a nightly build is and why teams rely on it, how it differs from a build that runs on every code change, how to schedule it with Jenkins’ timetable notation, what belongs inside it, how to keep it from overloading your machines, how to handle failures without blaming anyone, and how to avoid the traps that make nightly builds noisy or ignored. Every new word is explained the first time it appears, so you can start from zero.

1What Is a Nightly Build?

A nightly build is a build that runs automatically on a fixed schedule, usually once a day during quiet hours, regardless of whether anyone has just changed the code.

Let us start with the basics. Jenkins is a free automation server that builds, tests and delivers software. A build is one run of a job, such as one attempt to compile and test your code. A nightly build is a build that Jenkins starts by itself at a set time each night, so that no person needs to press any button.

The word “nightly” describes the usual timing, but it is really about a habit: a regular, unattended, thorough check of the whole product. Some teams run it at two in the morning. Others run it in the evening, right after the working day ends. Teams spread across the world may run it several times in a twenty-four hour cycle. What matters is that it is predictable, complete and automatic.

A nightly build usually differs from ordinary builds in three ways:

  • It is triggered by the clock, not by a code change. It runs whether or not anyone pushed new code that day.
  • It is bigger. It runs the long tests, the deep scans and the full packaging that a quick build skips.
  • It produces a daily snapshot. The result is a fresh, tested version of the whole product, often published as a “nightly” package that testers and colleagues can try.
Clock
Triggered by a schedule, not by a person
Deep
Runs the long tests and full checks
Daily
Gives the team a fresh report every morning
Analogy

A nightly build is like the annual health check-up a doctor might offer once a day instead of once a year. During the day you take your temperature now and then (quick builds). But once every night, a complete examination checks the heart, the lungs and the blood, and gives you a full report in the morning.

2Why Teams Run Nightly Builds

Some checks are too slow, too costly or too heavy to run on every single change. The night is the perfect home for them.

Consider a project whose complete test suite takes three hours. If it ran after every code push, a team of twenty developers pushing five times each would need a hundred three-hour runs a day, which is impossible. Yet skipping those tests altogether would let serious bugs slip through. The nightly build solves this: run the fast checks on every change, and run the slow, thorough checks once per night on the combined result of the whole day’s work.

Reason 1

Time for slow tests

Long integration, end-to-end and performance tests fit comfortably in hours when nobody is waiting on them.

Reason 2

Cheaper resources

Machines that sit idle at night can do the heavy work. Cloud servers used only for a few hours cost less than servers kept running all day.

Reason 3

A clean, from-scratch build

Starting from an empty workspace catches problems hidden by leftover files that quick incremental builds may keep.

Reason 4

A daily heartbeat

Even on a quiet day with no changes, the nightly run proves that the product still builds, and that the outside world, such as a changed library or server, has not broken it.

Reason 5

A fresh package to try

Testers, managers and other teams get a new, tested version every morning without asking anyone to prepare it.

Reason 6

Trend tracking

Running the same big checks every night produces a steady record of quality, speed and warnings over weeks and months.

i
Tip

A helpful way to decide what belongs in the nightly run: anything that is valuable but slower than a few minutes, or anything that needs lots of resources, is a candidate. Anything that a developer needs to know within minutes of a push belongs in the fast, on-change build.

Analogy

Think of a hotel. During the day, housekeeping does quick tidying between guests. But the deep clean of carpets, windows and mattresses happens at night, when rooms are empty and the work disturbs nobody. Nightly builds are the deep clean of software.

3Nightly Builds and Continuous Integration

Nightly builds do not replace fast builds on every change. They work together as two layers of safety.

Continuous Integration, often shortened to CI, is the habit of merging code often and checking every change automatically within minutes. In Jenkins, this usually means a build that starts by itself whenever code is pushed to the repository, triggered by a webhook, which is a small signal the code host sends. This layer gives quick feedback, so a developer learns about a mistake while it is still fresh in mind.

The nightly build is the second layer. It runs on a schedule and covers the heavy checks. Together they form a system in which the cheap checks run often and the expensive ones run regularly.

QuestionBuild on every changeNightly build
What starts it?A code push or pull requestThe clock
How long does it take?MinutesTens of minutes to hours
What does it check?Compile, fast unit tests, quick style checksEverything: long tests, deep scans, full packaging
Who is waiting for it?The developer who just pushedNobody, until the morning
What does a failure mean?This change probably broke somethingSomething in the combined work of the day, or in the outside world, broke
What does it produce?A pass or fail signalA pass or fail signal, plus reports and a daily package
Runs when there are no changes?NoYes, if scheduled by time
flowchart LR
    D["Developer pushes code all day"] --> F["Fast build on every change: minutes"]
    F -->|fast feedback| D
    F --> M["Code accumulates on the main branch"]
    M --> N["Nightly build starts at a set time"]
    N --> H["Heavy tests, deep scans, full packaging"]
    H --> R["Morning report and daily package"]
    R --> T["Team triages any failures"]
    T --> D
    
Figure 1: Fast builds give quick feedback all day, and the nightly build gives deep feedback every morning
Analogy

A smoke detector and a yearly fire inspection work together. The detector reacts within seconds to a real problem. The inspection goes through every corner, every wire and every exit, and finds slow, hidden hazards the detector would never notice. You want both.

4How Jenkins Schedules a Build

Jenkins has a built-in timekeeper. You describe the schedule in a compact notation, and Jenkins wakes the job up at the right moments.

In a Freestyle project, the option is called Build periodically, found in the Build Triggers section. In a Pipeline, the schedule is declared as a trigger inside the Jenkinsfile. In both cases, you write a schedule using the same short notation, borrowed from an old and widely used scheduling tool called cron.

sequenceDiagram
    participant T as Jenkins scheduler
    participant Q as Build queue
    participant A as Agent
    participant U as Team
    T->>T: Checks the schedule every minute
    T->>Q: Schedule matches, add a nightly build
    Q->>A: Assign to a free agent
    A->>A: Run the checks and package
    A-->>T: Report result and logs
    T->>U: Send notification on failure or recovery
    
Figure 2: The scheduler notices a matching time, queues the build, and an agent does the work
1

The scheduler checks the clock

Jenkins looks at its schedules about once a minute and compares them with the current time.

2

A schedule matches

When a job’s schedule matches the current minute, Jenkins creates a build for it.

3

The build enters the queue

Like every build, it waits for a free worker slot. If the night is quiet, it starts almost at once.

4

An agent runs it

A worker machine downloads the code, and the build steps run, just as in any other build.

5

Results are recorded and shared

Logs, reports and packages are saved, and notifications go out according to your rules.

!
Warning

Jenkins does not “catch up” on missed schedules. If Jenkins was switched off or restarting at the scheduled time, that night’s build simply does not happen, and Jenkins will not run it later on its own. Monitor for missing nightly runs, not only for failing ones.

Analogy

The Jenkins scheduler is like an alarm clock. It rings when the time matches, and a person, here the build queue, responds. But an alarm clock does not ring later to make up for a time it was unplugged. If the power was out at six o’clock, the alarm never sounds.

5Reading and Writing a Schedule

The schedule notation looks strange at first, but it has only five fields, and each has one simple meaning.

A Jenkins schedule is written as five values separated by spaces, always in the same order.

PositionFieldAllowed valuesExample meaning
1Minute0 to 59The minute of the hour
2Hour0 to 23The hour of the day, in 24-hour form
3Day of the month1 to 31Which date
4Month1 to 12Which month
5Day of the week0 to 7, where both 0 and 7 mean SundayWhich weekday

Some special symbols make schedules easier to write. A star, *, means “every”. A comma separates a list, such as 1,3,5. A dash makes a range, such as 1-5 for Monday to Friday. A slash makes a step, such as */15 for “every fifteen”.

The magic letter H

Jenkins adds a special symbol of its own: the letter H, which stands for hash. Instead of a fixed minute, H tells Jenkins, “Pick a steady but spread-out moment for this job.” Jenkins chooses the exact minute by a calculation based on the job’s name, so the same job always gets the same minute, while different jobs get different ones.

Why is this so useful? Suppose a hundred jobs all say “run at exactly two o’clock”. At two o’clock sharp, a hundred builds flood the queue at once, machines struggle, the code server is hammered by a hundred simultaneous downloads, and after the burst everything sits idle. Using H in the minute field spreads those hundred starts across the hour, which smooths the load without any extra effort.

SchedulePlain-words meaning
H 2 * * *Once a day, at some minute during the two o’clock hour
H H(0-3) * * *Once a day, at a spread-out time somewhere between midnight and 3 a.m.
H 2 * * 1-5Once a day in the two o’clock hour, on weekdays only
H 3 * * 0Once a week, on Sunday in the three o’clock hour
H 1 1 * *Once a month, on the first day, around one in the morning
H H/6 * * *Every six hours, with the minute spread out
@midnightA shortcut meaning once a day, at a spread-out time around midnight
@dailyA shortcut for once a day, at a spread-out time
@weekly and @monthlyShortcuts for once a week and once a month, at spread-out times
i
Tip

For a nightly build, an hour range such as the one written H(0-3) is a friendly choice. It says “sometime in the small hours” and lets Jenkins spread many nightly jobs across those hours, so they do not all start together.

Where do you type the schedule?

  • Freestyle project: tick “Build periodically” in the Build Triggers section and enter the schedule in the box. Jenkins shows a helpful note under the box, explaining when the next runs will happen.
  • Declarative Pipeline: declare a trigger of the cron kind inside the Jenkinsfile, with the schedule as its text. The Pipeline registers the schedule the first time it runs, so the job must run once before the schedule takes effect.
  • Multibranch Pipeline: the trigger is declared in the Jenkinsfile of each branch, so it applies to the branches that contain it. Many teams prefer to schedule only the main branch, and use a separate dedicated job for heavy nightly work.
Analogy

The letter H is like a receptionist who staggers appointments. Instead of telling every visitor “come at nine o’clock sharp”, the receptionist gives each one a slightly different time within the morning. The office never has a crowd at the door, and the same visitor always gets the same slot.

6Time Zones, Daylight Saving and the Meaning of “Night”

A schedule is a promise about time, and time is surprisingly slippery.

By default, Jenkins reads schedules in the time zone of the Jenkins server itself. If the server is in a data centre in another country, “two o’clock” may not be night for your team at all. Jenkins allows you to name a time zone at the top of the schedule, on its own line, by writing a line starting with TZ= followed by a standard zone name. This makes the intention explicit and independent of where the server happens to run.

Zone

Server time

Without an explicit zone, schedules follow the server’s clock. Moving the server to another region silently moves your nightly build.

Zone

Named time zone

Adding a TZ line pins the schedule to a chosen zone. It is the clearest option for teams in one region.

Season

Daylight saving

When clocks jump forward or back, a time in the small hours may be skipped or happen twice. Avoid scheduling important jobs in the exact hour when clocks change.

Global

Teams across time zones

For a worldwide team there is no single night. Run several scheduled builds, each shortly after a region finishes its working day, or run one at a time that suits the majority.

The idea of “night” itself deserves thought. The point of the nightly build is to finish while people are away, so the result is ready when they return. Choose a start time by working backwards from the moment the team begins work. If the build takes four hours and the team starts at nine, then starting at two in the morning leaves a comfortable margin, while starting at six would leave people staring at a build still running.

!
Warning

Do not schedule a nightly build so late that it may still be running when the workday begins. A build that overlaps with the morning rush competes with developers’ quick builds for machines and slows everyone down.

Analogy

Choosing the start time is like planning when to put a roast in the oven for a dinner party. You work backwards from when the guests arrive, allow for the cooking time, and add a little margin in case something takes longer than expected.

7Scheduled Builds Versus Polling for Changes

Jenkins has two clock-based triggers that look similar but behave very differently. Knowing which to use avoids wasted work.

The trigger called Build periodically starts a build at the scheduled time, always, no matter what. The trigger called Poll SCM, where SCM means source code management, uses a schedule only to ask the repository whether anything has changed. If the answer is yes, it starts a build. If no, nothing happens.

QuestionBuild periodicallyPoll SCM
What does the schedule do?Starts a buildChecks for changes
Builds when there are no changes?YesNo
Best forNightly full checks that must always runSaving effort when nothing changed
Catches outside changes?Yes, such as a library that changed or a server that stopped answeringNo, because it only looks at your own repository
Uses fewer resources?NoYes, when the repository is quiet
flowchart TD
    S["I want a scheduled build"] --> Q1{"Must it run even if the code did not change?"}
    Q1 -->|Yes| BP["Use Build periodically"]
    Q1 -->|No| Q2{"Only build when there are new commits?"}
    Q2 -->|Yes| PS["Use Poll SCM with a nightly schedule"]
    Q2 -->|No| BP
    BP --> N1["Good for catching outside changes, such as libraries and servers"]
    PS --> N2["Good for saving resources on quiet days"]
    
Figure 3: Choose between a build that always runs and one that runs only when the code changed

A subtle but important point: “no change in your code” does not mean “nothing could break”. A library your project downloads might have released a new version that breaks something. A test server might have changed. A certificate might have expired. A nightly build that always runs will catch these outside changes, while one that runs only on code changes will stay silent until someone happens to push. This is a real reason to prefer the always-run trigger for your main nightly job.

i
Tip

Many teams use both. The fast build reacts to each push, and a nightly always-run build catches everything that changes outside the repository. If resources are tight, consider the polling version for secondary branches and the always-run version for the main branch.

Analogy

Poll SCM is like checking the mailbox each evening and only opening letters if any arrived. Build periodically is like doing your full evening routine every day, whether or not any mail came. The second is more thorough, because problems can arrive by other routes than the post.

8What Belongs Inside a Nightly Build

The nightly build is the place for everything valuable that is too slow or too heavy for the fast build.

ActivityWhat it doesWhy it fits the night
Clean, from-scratch buildDeletes the workspace and builds everything anewSlower than incremental builds, but exposes hidden dependencies on leftover files
Full test suiteRuns every unit, integration and end-to-end testCan take hours, and nobody waits for it
Cross-platform buildsBuilds and tests on several operating systems and versionsNeeds many machines at once
Performance and load testsMeasures speed and behaviour under heavy useNeeds quiet machines for stable numbers
Security scansChecks code and libraries for known weaknessesScanners update daily and can be slow
Dependency checksLooks for outdated or vulnerable librariesFinds problems that arise without any code change
Static code analysisDeep examination of code quality and complexityHeavy processing, useful trends
Container image build and scanBuilds images and checks their contentsLarge downloads and long scans
Documentation buildGenerates guides and reference pagesNot urgent, but useful to keep current
Nightly packagingProduces a versioned package for testersGives everyone a fresh version each morning
HousekeepingCleans old files, caches and imagesSafe to do when systems are quiet

Why deep tests belong at night

There is a classic idea in testing, often shown as a pyramid. At the bottom are many small, very fast tests that check tiny pieces of code. In the middle are fewer, slower tests that check pieces working together. At the top are a handful of very slow tests that behave like a real user going through the whole product. The fast tests belong in the build on every change. The slow ones at the top of the pyramid are exactly the ones that fit a nightly run.

flowchart TD
    A["Nightly build starts"] --> B["Clean workspace and full checkout"]
    B --> C["Compile everything from scratch"]
    C --> D["Run unit tests"]
    D --> E["Run integration tests"]
    E --> F["Run end-to-end and performance tests"]
    F --> G["Run security and dependency scans"]
    G --> H["Publish reports and quality trends"]
    H --> I{"All checks passed?"}
    I -->|Yes| J["Create and publish the nightly package"]
    I -->|No| K["Send failure notification with a link to the log"]
    J --> L["Send recovery notice if the last night failed"]
    
Figure 4: A typical shape of a nightly Pipeline, from a clean start to a published package
i
Tip

Keep the stages in a sensible order. Put quick checks first and slow ones last, so that if a basic compile fails, the build stops in minutes instead of waiting hours before telling you the obvious.

Analogy

A nightly build is like the complete rehearsal of a play. During the day, actors practise single scenes quickly. But once each night, the whole cast performs the full show with lights, music and costumes, because some problems only appear when everything happens together.

9The Nightly Package: Versions and Artifacts

One of the most useful outputs of a nightly build is a fresh package that anyone can try the next morning.

An artifact is any file a build produces that you want to keep, such as an installable program, a container image or a test report. A nightly build usually publishes a nightly package: a complete, tested version of the product made from the latest code. Testers can install it, product managers can watch progress in it, and other teams that depend on your work can try it.

Naming nightly packages

Good names tell people exactly what they are getting. A common habit is to combine the planned version, the word nightly, the date and the short commit fingerprint. Jenkins provides variables that make this easy: the build number, the date, and the commit hash. A name built this way lets anyone trace a package back to the exact code that made it.

Ingredient in the nameWhere it comes fromWhy it helps
Planned versionThe project’s current version settingShows what release this is heading towards
The word nightlyA fixed labelMakes it obvious this is not an official release
The dateThe date of the buildMakes sorting and finding easy
Build numberA built-in Jenkins variableLinks to the exact build page
Commit fingerprintThe Git plugin’s variablesPoints to the exact source

Where to store them

Jenkins can keep archived artifacts with each build, but it is not meant to be a long-term file store, and nightly packages are big and frequent. Publish them to a proper artifact repository, a dedicated service that stores versioned packages, and keep only recent nights. Old nightly packages are rarely useful, and they consume disk space quickly.

!
Warning

Never let a nightly package be mistaken for an official release. Use a clear name, a separate storage location, and a short retention period, so that nobody accidentally ships yesterday’s experimental version to customers.

Analogy

A nightly package is like the “today’s batch” tray in a bakery window. It is fresh, labelled with the date, and available to try. Tomorrow it will be replaced, and it is never mixed up with the boxed, guaranteed goods on the shelf behind.

10Resources, Agents and Cost

Nightly builds can be very heavy. Planning the machines behind them keeps the night smooth and the bill reasonable.

Quick reminder of two words. The controller is the brain of Jenkins. An agent is a worker machine where the build steps actually run. An executor is a slot on an agent that can run one build at a time.

At night, many jobs may want to run together. If forty nightly jobs are scheduled and you have ten executors, thirty jobs will wait in the queue. This is not a disaster, but it means your last jobs may finish much later than planned. Three tools help.

Spread

Spread the start times

Use the H symbol and hour ranges, so that jobs start across several hours instead of at one instant.

Scale

Temporary agents

Create workers only for the night and remove them in the morning, on the cloud or on Kubernetes. You pay only for what you use.

Order

Prioritise important jobs

Give the most important nightly jobs the earliest slots, so that if the night runs long, the least important ones are the ones left waiting.

Limit

Throttle heavy jobs

Restrict how many heavy builds may run together, so that shared resources such as test databases are not overwhelmed.

sequenceDiagram
    participant S as Scheduler
    participant C as Controller
    participant K as Cloud or Kubernetes
    participant A as Temporary Agents
    S->>C: Night begins, many nightly jobs due
    C->>K: Request extra agents
    K->>A: Create agents
    A->>C: Connect and ask for work
    C->>A: Send nightly builds
    A-->>C: Results and logs
    C->>K: Queue empty, release the agents
    K->>A: Delete the agents
    
Figure 5: Temporary agents appear for the night and disappear when the work is done

Protecting shared systems

Nightly tests often use shared resources: a test database, a shared server, a licensed tool. Two builds that use the same test database at the same moment can corrupt each other’s data and produce mysterious failures. The Pipeline option that disallows concurrent builds of the same job stops the same job from overlapping with itself, and throttling or locking plugins can serialise access to shared resources between different jobs.

!
Warning

A nightly job that takes longer than a day will overlap with the next night’s run, and the queue slowly fills. Set time limits on the whole build, so that a stuck run stops itself and frees its resources instead of poisoning the following nights.

Analogy

Scheduling many nightly jobs is like managing a laundromat overnight. If everyone arrives at ten o’clock sharp, there are not enough machines. If arrivals are spread across the evening, and the owner rents extra machines only for the busy hours, everybody’s washing is done by morning at a sensible cost.

11Notifications and the Morning Report

A nightly build nobody reads is wasted electricity. The value comes from what happens when the team arrives.

The goal is simple: when people start work, they should know at a glance whether last night was healthy, and if not, exactly what broke and who should look. Notifications and dashboards make that possible.

ChannelBest useTip
EmailA summary sent to the responsible team when the build fails or recoversInclude the job name, the build link and the first error, not the whole log
Team chat messageA short, visible message in the team’s channelPost only on failure and recovery to avoid noise
Dashboard viewA screen showing the colour of every nightly jobDisplay it on a shared screen so a red job is impossible to miss
Commit status or ticketLinking a failure to the suspected change or opening an issue automaticallyAutomatic tickets should be used sparingly, and grouped by cause
Trend graphsTest counts, duration and warnings across nightsReview weekly to spot slow decay

Good notification design is about restraint. A message every night, even on success, becomes wallpaper that people stop reading. A better pattern is to notify when the state changes: tell people when the nightly first fails, and again when it recovers. Nights of steady success stay quiet, and a red night stands out.

i
Tip

Send the failure message to the team that owns the failing part, not to everyone. A message that reaches only the people who can act on it gets acted on. A message that reaches the entire company gets ignored.

Analogy

A good morning report is like a weather forecast on the news. It does not read out every measurement taken overnight. It tells you: sunny, or take an umbrella, and only where it matters to you.

12Handling Failures: The Morning Triage

Failure is normal in a nightly build. What matters is how quickly and calmly the team responds.

When a nightly build fails, many hands may have touched the code since the last good run, so finding the cause takes more detective work than with a fast build that has a single suspect. A simple, agreed routine, often called triage, keeps the response smooth. Triage means sorting problems by urgency and cause so the right person can act.

flowchart TD
    F["Nightly build failed"] --> R["Owner of the day reads the log"]
    R --> Q1{"Is it an environment problem?"}
    Q1 -->|Yes| E["Fix or report: agent, network, disk or outside service"]
    Q1 -->|No| Q2{"Is it a flaky test?"}
    Q2 -->|Yes| FL["Quarantine the test and open a ticket to fix it"]
    Q2 -->|No| Q3{"Which commits since the last good night?"}
    Q3 --> BS["Find the change, contact its author, and fix or revert"]
    E --> RB["Rerun the nightly to confirm"]
    FL --> RB
    BS --> RB
    RB --> OK["Green again, send a recovery message"]
    
Figure 6: A calm decision path for the morning after a failed nightly
1

Assign an owner for the morning

A rotating “nightly owner” reads the report first, so that responsibility is never everybody’s and therefore nobody’s.

2

Read the Console Output

Start from the bottom, find the first real error, and note the stage and step that failed.

3

Classify the cause

Was it the environment, a flaky test, or a real bug introduced by a recent change?

4

Use the change list

Jenkins lists the commits included since the last successful build. That list narrows the suspects.

5

Fix or revert quickly

If the cause is a bad change, fix it or roll it back so the main branch returns to health.

6

Confirm with a rerun

Run the nightly again, manually if needed, and announce the recovery.

The trouble with flaky tests

A flaky test is a test that sometimes passes and sometimes fails without any change to the code. Long nightly suites collect flaky tests over time, and they are dangerous. If people learn that “the nightly is often red for no reason”, they stop trusting it, and real failures slip by unnoticed. Treat flaky tests as bugs. Track them, quarantine the worst offenders so that they do not block the result, and fix them on a schedule.

!
Warning

A nightly build that is permanently red is worse than having no nightly build at all. It teaches the team to ignore red. Keep the nightly green by fixing failures quickly, and never accept a “usually red” status as normal.

Analogy

A flaky test is like a car alarm that goes off on its own every few nights. After a week, the neighbours stop looking out of the window. When a real thief arrives, nobody reacts. Fix the false alarms so that the real ones are heard.

13Freestyle and Pipeline Nightly Jobs

You can set up a nightly build in either job type. The idea is the same, but the experience differs.

QuestionFreestyle projectPipeline
Where is the schedule set?Build Triggers, Build periodically boxA trigger declared in the Jenkinsfile
Where is the schedule stored?Inside JenkinsIn your repository, reviewed with the code
Stages and parallel workAwkward, needs several linked projectsNatural, with stages and parallel branches
Time limits and retentionBuild environment optionsPipeline options at the top of the file
Best forA simple nightly task, such as one scriptA full nightly flow with many stages

Useful Pipeline options for nightly jobs

Option

Timeout for the whole run

Stops a stuck build so it cannot block the next night or hold machines forever.

Option

Disable concurrent builds

Prevents two runs of the same nightly from overlapping.

Option

Build discarder

Keeps only the last several nights of history and artifacts to save disk space.

Option

Timestamps

Adds the time to every log line, so you can see which stage ate the hours.

Option

Post actions

Run steps whatever the result, such as cleaning up, publishing reports and sending notifications.

Option

Agent labels

Send the job to agents that have the right tools and enough power.

i
Tip

Because the cron trigger in a Pipeline is registered when the Pipeline runs, run the job manually once after you add or change the schedule. Then open the job’s configuration and check that Jenkins shows the schedule you expect.

14Monitoring the Nightly Builds Themselves

The nightly build watches your software. Someone must watch the nightly build.

Signal

Did it run at all?

Because Jenkins never catches up on missed schedules, a missing run is a silent failure. Check that each expected nightly job has a build for last night.

Signal

Duration trend

A nightly that slowly grows from two hours to five will one day overlap with the morning. Watch the trend and act early.

Signal

Failure rate and streaks

Count how many nights in the last month were red, and how long each red streak lasted.

Signal

Queue wait time

If nightly jobs wait long for a free machine, add capacity or spread the schedule.

Signal

Test count and flakiness

A drop in the number of tests may mean tests were silently skipped. Track counts as well as results.

Signal

Disk and cost

Watch storage used by nightly artifacts and the bill for temporary machines.

An especially useful trick is a watchdog: a tiny check, run each morning, that confirms every expected nightly job finished within its expected window and complains loudly if one did not. It turns the silent failure of a missed schedule into a visible one.

!
Warning

A “green” dashboard can hide a nightly job that did not run for a week, because the last result is still green. Show the age of the last run next to its colour, so that stale results look stale.

Analogy

A watchdog check is like a night guard who signs a logbook at every round. If the entry for two o’clock is missing, the manager knows the guard did not do the round, even though nothing was stolen.

15Security and Safety for Unattended Builds

A build that runs alone at night has no human watching. That calls for extra care.

Secrets

Use the credentials store

Nightly jobs often deploy or publish. Give them credentials from the secure vault, bound only where needed, never typed into scripts.

Rights

Least privilege

An unattended job should have only the permissions it truly needs. A publishing job should not be able to delete production data.

Approval

No unattended production deploys

Nightly builds may publish a nightly package, but releasing to real customers should still need a human decision.

Isolation

Use agents, not the controller

Heavy and untrusted work belongs on agents so a runaway build cannot damage the brain of Jenkins.

Trust

Build only trusted code

A scheduled job that builds a branch from strangers would run their code with your secrets. Limit it to trusted branches.

Audit

Keep logs

Retain enough history to answer “what ran last Tuesday and with which code?” if questions arise.

!
Warning

Be careful with nightly jobs that clean things up. A clean-up that deletes files, images or cloud resources runs with nobody watching. Restrict what it may remove, test it on a practice system, and add safety checks that refuse to run against the wrong target.

Analogy

Giving an unattended job broad permissions is like leaving a night cleaner with the master key, a blank cheque and no supervision. Give the cleaner only the keys for the rooms they clean, and check the logbook in the morning.

16Advantages, Disadvantages and Trade-offs

Nightly builds are very valuable, and they have real costs.

Advantages

  • Runs slow, thorough checks without making anyone wait.
  • Uses idle night-time machines, and cheap temporary capacity.
  • Catches problems caused by outside changes, not only by your code.
  • Provides a fresh, tested package and report every morning.
  • Builds from scratch, exposing hidden dependencies on leftovers.
  • Creates trend data on quality, speed and warnings.

Disadvantages and costs

  • Feedback is slow: a bug can wait up to a day to be found.
  • Many commits may be in one failing run, so finding the culprit is harder.
  • Long suites collect flaky tests that erode trust.
  • Heavy jobs cost machine time and money.
  • A missed schedule is silent unless monitored.
  • Failures that nobody triages become a background of red.

The main trade-off is depth versus speed of feedback. A nightly build gives the deepest checking but the slowest reaction. That is exactly why it complements, and never replaces, the fast build on every change. Use the fast build to catch mistakes within minutes, and the nightly build to catch everything else within hours.

The fast build tells you about your mistake. The nightly build tells you about everyone’s.

17Design Patterns and Anti-patterns

A pattern is a proven habit. An anti-pattern is a tempting shortcut that causes trouble later.

Patterns worth copying

Pattern

Fast build plus nightly build

Run quick checks on every change and the deep checks nightly, so the team gets speed and depth together.

Pattern

Spread the schedule

Use the H symbol and hour ranges so jobs do not pile up at one instant.

Pattern

Fail fast inside the nightly

Order stages from quick to slow, so simple problems stop the run early.

Pattern

Owner of the morning

A rotating person checks the nightly result first, every day.

Pattern

Notify on state change

Message the team when the nightly turns red and when it recovers, not every night.

Pattern

Watchdog for missing runs

A simple morning check that confirms every expected job ran on time.

Pattern

Temporary agents for the night

Create workers on demand and release them afterwards to control cost.

Pattern

Short retention for nightly packages

Keep only a week or two of nightly artifacts in a proper repository.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
What people do

They schedule every nightly job at exactly the same minute, such as midnight.

Why it hurts

Machines and code servers are overwhelmed at that instant, queues explode, and many jobs finish late or fail from resource shortages.

Better approach

Use H in the minute field and hour ranges, so starts are spread out.

ANTI-PATTERN 02Avoid
What people do

They accept a permanently red nightly and say “it always fails, ignore it”.

Why it hurts

Real failures hide inside the noise, and trust in the whole automation collapses.

Better approach

Fix or quarantine the failing tests, and treat a red nightly as a priority for the morning owner.

ANTI-PATTERN 03Avoid
What people do

They put everything into the fast build, including the three-hour tests, “to be safe”.

Why it hurts

Developers wait hours for feedback, machines are saturated, and people learn to skip the checks or batch their changes.

Better approach

Keep the fast build quick, and move slow checks to the nightly build.

ANTI-PATTERN 04Avoid
What people do

They let nightly builds run with no time limit and no retention rules.

Why it hurts

A stuck build blocks the next night, and old logs and packages fill the disk until Jenkins slows or fails.

Better approach

Set a timeout for the whole run, disable overlapping runs, and keep only recent history and artifacts.

ANTI-PATTERN 05Avoid
What people do

They depend on the nightly build to deploy straight to customers with nobody approving.

Why it hurts

A bad night’s build reaches real users before anyone has looked at it.

Better approach

Publish nightly packages to a test area, and require a human decision to release.

18Best Practices and Common Mistakes

Small habits decide whether the nightly build is a trusted friend or ignored background noise.

Best practices

  • Split fast and deep. Keep quick checks on every change, and heavy checks in the nightly build.
  • Use H and hour ranges. Spread the load across the night.
  • State the time zone. Do not depend on where the server happens to live.
  • Avoid the daylight-saving change hour. Skipped or doubled hours can cause surprises.
  • Always run from a clean workspace. Start from scratch to expose hidden assumptions.
  • Order stages from fast to slow. Fail early on simple problems.
  • Set timeouts and disable overlap. A stuck build must never poison the next night.
  • Publish a clearly named nightly package. Include date, build number and commit, and store it separately from releases.
  • Assign a morning owner. Someone always reads the result.
  • Notify on change of state. Failure and recovery, not every night.
  • Watch for missing runs. Jenkins will not catch up on its own.
  • Track trends. Duration, test counts, warnings and failure streaks.
  • Prune history. Keep a sensible number of recent nights.

Common mistakes

!
Mistake

Assuming the nightly ran because the dashboard is green. The colour shows the last result, which might be a week old. Check the time of the last run, not only its colour.

!
Mistake

Forgetting to run a new Pipeline once after adding a cron trigger. The schedule is registered only when the Pipeline runs, so the first nightly may never fire.

!
Mistake

Letting the nightly grow without limit. A suite that adds ten minutes every month becomes unmanageable in a year. Review durations regularly and split or trim.

!
Mistake

Sharing test data between simultaneous jobs. Two nightly jobs writing to the same test database will corrupt each other. Give each job its own data, or serialise access.

19Real-World Usage Patterns

Different teams use the nightly idea in different ways. Here are common shapes.

The small team’s safety net

A team of five runs quick unit tests on every push, and one nightly job that builds from scratch, runs the complete suite and emails the result. Setup takes an afternoon, and it catches the slow problems the quick build cannot.

The product team with daily packages

A product team publishes a nightly installable package every morning. Testers and product managers install it first thing, try the newest features, and report issues against a specific dated version, which makes bug reports precise.

The multi-platform build

A team supporting several operating systems runs a nightly build across all of them in parallel on temporary machines. What would take a full day one after another finishes in a few hours side by side, and the team pays for the machines only while they run.

The security and dependency sweep

A security-minded team runs a nightly scan of code and libraries against the latest lists of known weaknesses. Because the lists change daily, the nightly run discovers new problems in unchanged code, and opens an alert before anyone has pushed a single line.

The performance tracker

A team measures response speed and memory use with a fixed load test every night, on quiet, identical machines. Graphs of the numbers show exactly which day a slowdown began, and the change list of that day points at the cause.

The worldwide team

A company with teams on three continents runs several scheduled builds, each shortly after one region ends its day. Every region wakes up to a fresh result that includes the work of the others, so “night” always exists somewhere.

The housekeeping crew

Not every nightly build compiles software. An operations team uses scheduled jobs for backups, cleaning old cloud resources and rotating logs. The same scheduling and notification tools serve any repeatable unattended task.

20Frequently Asked Questions

Q1What is a nightly build in Jenkins, in one sentence?
It is a build that Jenkins starts automatically on a schedule, usually once a night, to run the thorough, slow checks and produce a fresh report and package for the team’s morning.
Q2How do I schedule a nightly build?
In a Freestyle project, tick Build periodically under Build Triggers and enter a schedule. In a Pipeline, declare a cron trigger in the Jenkinsfile. A common choice is a schedule meaning “once a day at a spread-out time in the two o’clock hour”.
Q3What does the letter H mean in a Jenkins schedule?
It stands for hash. Jenkins picks a steady but spread-out value for that field, based on the job name, so that many jobs do not all start at the same instant.
Q4What is the difference between Build periodically and Poll SCM?
Build periodically always starts a build at the scheduled time. Poll SCM uses the schedule only to check the repository, and builds only if there are new changes. Use the first for a nightly build that must always run, and the second to save effort on quiet days.
Q5Which time zone does Jenkins use?
By default, the time zone of the Jenkins server. You can name a zone explicitly by adding a line beginning with TZ= at the top of the schedule, which makes the intention clear regardless of where the server runs.
Q6What happens if Jenkins is down at the scheduled time?
The build for that time is simply missed. Jenkins does not run missed schedules later. Monitor that each nightly job actually produced a build, for example with a morning watchdog check.
Q7What should I put in a nightly build?
The slow and heavy work: a clean build from scratch, the complete test suite, cross-platform checks, performance tests, security and dependency scans, static analysis, and packaging of a nightly version.
Q8Should nightly builds replace builds on every commit?
No. They complement each other. Fast builds on every change give quick feedback to the developer. The nightly build gives deep, thorough checking of the combined work and the outside world.
Q9How do I stop many nightly jobs from overloading Jenkins?
Spread start times with H and hour ranges, use temporary agents for extra capacity, prioritise the most important jobs, and throttle heavy jobs that share resources.
Q10What should I do when the nightly build fails?
Have a morning owner read the Console Output from the bottom up, classify the cause as environment, flaky test or real change, use the change list to find the suspect commits, fix or revert quickly, and rerun to confirm recovery.
Q11Why did my new Pipeline schedule not start the build?
A cron trigger declared in a Jenkinsfile is registered when the Pipeline runs. Run the job manually once after adding or changing the schedule, then check that Jenkins shows the expected schedule in the job configuration.

21Summary and Key Takeaways

A nightly build is Jenkins’ after-hours inspection. While the team sleeps, Jenkins wakes on a schedule, builds everything from scratch, runs the slow and thorough checks, scans for weaknesses, packages a fresh version and leaves a report waiting for the morning. It complements the fast build on every change, giving the team speed during the day and depth overnight.

Making it work well is mostly about habits. Write schedules with the H symbol and a clear time zone, spread the load across the night, order stages from fast to slow, and protect machines with time limits and no overlapping runs. Publish clearly named nightly packages, notify on changes of state, assign a morning owner, and watch for runs that never happened. Do these things, and the nightly build becomes the quiet, dependable heartbeat of your project.

Key Takeaways

  • A nightly build is a scheduled, unattended, thorough build, triggered by the clock rather than by a code change, and it complements the fast build that runs on every push.
  • Schedules use five fields: minute, hour, day of month, month and day of week. The letter H spreads start times across the hour, and hour ranges spread jobs across the night.
  • Choose the right trigger. Build periodically always runs and catches outside changes. Poll SCM builds only when the code changed and saves effort on quiet days.
  • Put slow and heavy work in the nightly build: clean builds, the full test suite, cross-platform runs, performance tests, security and dependency scans, and nightly packaging.
  • Protect your machines. Use temporary agents, throttle shared resources, set timeouts, disable overlapping runs and keep short retention for history and artifacts.
  • Make the result useful. Publish clearly named nightly packages, notify on failure and recovery, assign a morning owner and triage failures calmly, fixing flaky tests so the nightly stays trustworthy.
  • Watch the watcher. Jenkins never catches up on missed schedules, so monitor that each nightly ran, track duration and failure trends, and treat a permanently red nightly as a problem to fix.