Skip to content

Your first scheduled cron

This is a guide to creating a cron job that sends you a weather email every morning.

Step 1: Sign up to Val Town

Sign up to Val Town. It’s free.

Step 2: Set up a Cron Trigger

Create a new val or use an existing one. Add a new TypeScript file to your val. In the file editor, set its trigger type to Cron via the UI.

This will create a scheduled trigger associated with this file. The default code will look like this:

weatherNotifier.ts
export default async function (interval: Interval) {
// your code…
}

This function will be run on a schedule. By default, this runs every hour. You can change the frequency by clicking the clock icon in the top right corner.

Step 3: Get the weather

In the following example code, we are using getWeather from stevekrouse/getWeather. It uses the free wttr.in service to get weather data.

  1. Add these lines to your code
Step 3Run in Val Town ↗
import { getWeather } from "https://esm.town/v/stevekrouse/getWeather";
export default async function (interval: Interval) {
let weather = await getWeather("Brooklyn, NY");
console.log(weather.current_condition[0].FeelsLikeF);
}
  1. Replace Brooklyn, NY with your location
  2. Click Run
  3. View the output in the val’s logs

Step 4: Send yourself an email

We’re going to use std/email to send an email to yourself.

  1. Add these lines to your code
Step 4
import { email } from "https://esm.town/v/std/email";
import { getWeather } from "https://esm.town/v/stevekrouse/getWeather";
export default async function (interval: Interval) {
let weather = await getWeather("Brooklyn, NY");
let feelsLike = weather.current_condition[0].FeelsLikeF;
let description = weather.current_condition[0].weatherDesc[0].value;
await email({
subject: `Weather now is ${description} and ${feelsLike}°F`,
});
}
  1. Click Run
  2. Check your email inbox

You should have an email with a subject like “Weather now is Sunny and 67°F”.

Step 5: Schedule the Job

We want this to run every morning. For example, in NYC, you could use 0 9 * * * to run at 5am ET every morning.

We recommend crongpt.com to help you write cron expressions. It also handles the timezone conversion from your timezone to Val Town’s server timezone (UTC).

  1. Go to crongpt.com and generate your cron expression
  2. Click the clock icon (or find the schedule settings) in the file editor for your weatherNotifier.ts file.
  3. Click Cron
  4. Paste in your cron expression.

Next steps

🥳 Congratulations! You’ve created a Cron job that sends you a weather notification every morning. You can customize it to your needs. There are a LOT of weather vals you can use or get inspiration from: