Scheduled Bots (Cron Jobs)
NerdHosting supports two execution modes for your bots:
24/7 Persistent Mode
Bot runs continuously, always online.
Best for:
- Discord chat bots
- Telegram message handlers
- Real-time monitoring
- Event-driven bots
Scheduled Mode (Cron)
Bot runs at specific intervals, then exits.
Best for:
- Daily social media posts
- Periodic data collection
- Scheduled reports
- Cleanup tasks
⏰ How Scheduled Bots Work
When you set a bot to scheduled mode:
- Your bot code runs at the scheduled time
- Bot completes its task (posts, fetches data, etc.)
- Bot exits naturally (no infinite loops needed!)
- Platform automatically restarts it at the next scheduled time
Minimum Interval: 20 Minutes
To prevent server abuse, scheduled bots cannot run more frequently than every 20 minutes.
📅 Schedule Presets (Easy Mode)
Choose from common presets in the dashboard:
⏰ Every 20 minutes
⏰ Every 30 minutes
⏰ Every hour
⏰ Every 2 hours
⏰ Every 6 hours
⏰ Every 12 hours
⏰ Once daily
🔧 Custom Cron Expressions (Advanced)
For advanced users, enter custom cron expressions:
# Format: minute hour day month weekday
*/20 * * * * # Every 20 minutes
0 * * * * # Every hour at minute 0
30 2 * * * # Daily at 2:30 AM
0 */6 * * * # Every 6 hours
0 9 * * 1 # Every Monday at 9 AM
💻 Scheduled Bot Code Example
Write code that runs once and exits (no setInterval or infinite loops!):
// Bluesky Daily Poster (JavaScript)
const axios = require('axios');
async function main() {
// Login to Bluesky
const session = await axios.post('https://bsky.social/xrpc/com.atproto.server.createSession', {
identifier: process.env.BSKY_USERNAME,
password: process.env.BSKY_APP_PASSWORD
});
// Post message
await axios.post('https://bsky.social/xrpc/com.atproto.repo.createRecord', {
repo: session.data.did,
collection: 'app.bsky.feed.post',
record: {
$type: 'app.bsky.feed.post',
text: `Daily update: ${new Date().toISOString()}`,
createdAt: new Date().toISOString()
}
}, {
headers: { Authorization: `Bearer ${session.data.accessJwt}` }
});
console.log('Posted successfully!');
// Script exits here - platform will restart at next schedule
}
main();
# Python Data Collector (runs every hour)
import os
import requests
from datetime import datetime
def main():
# Fetch data from API
response = requests.get('https://api.example.com/data')
data = response.json()
# Process and save
print(f"Collected {len(data)} items at {datetime.now()}")
# Exit naturally - will run again in 1 hour
if __name__ == "__main__":
main()
🎯 Do's and Don'ts for Scheduled Bots
✅ DO:
- Write code that runs once and exits
- Use
async/await properly
- Log your actions for debugging
- Handle errors gracefully
❌ DON'T:
- Use
setInterval() or setTimeout()
- Create infinite loops
- Keep WebSocket connections open
- Add event listeners that prevent exit
Tip: You can convert any existing bot between persistent and scheduled mode using the "Edit Schedule" button on your dashboard!
Example Bot Code
Discord Bot Example
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on('messageCreate', message => {
if (message.content === '!ping') {
message.reply('Pong!');
}
});
// Use environment variable from dashboard
client.login(process.env.DISCORD_TOKEN);
Bluesky Bot Example
const { BskyAgent } = require('@atproto/api');
const agent = new BskyAgent({
service: 'https://bsky.social'
});
async function main() {
// Login with credentials from dashboard
await agent.login({
identifier: process.env.BLUESKY_HANDLE,
password: process.env.BLUESKY_APP_PASSWORD
});
console.log('Bot is running!');
// Check notifications every 5 minutes
setInterval(async () => {
const notifs = await agent.listNotifications();
console.log(`New notifications: ${notifs.data.notifications.length}`);
}, 300000);
}
main();
Telegram Bot Example
const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
bot.start((ctx) => {
ctx.reply('Welcome! I am your bot.');
});
bot.command('ping', (ctx) => {
ctx.reply('Pong! 🏓');
});
bot.on('text', (ctx) => {
console.log(`Message from ${ctx.from.username}: ${ctx.message.text}`);
});
bot.launch();
console.log('Telegram bot is running!');
Slack Bot Example
const { App } = require('@slack/bolt');
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
app.message('hello', async ({ message, say }) => {
await say(`Hey there, <@${message.user}>!`);
});
app.command('/ping', async ({ command, ack, respond }) => {
await ack();
await respond('Pong! 🏓');
});
(async () => {
await app.start(process.env.PORT || 3000);
console.log('⚡️ Slack bot is running!');
})();
Twitch Bot Example
const tmi = require('tmi.js');
const client = new tmi.Client({
options: { debug: true },
identity: {
username: process.env.TWITCH_USERNAME,
password: process.env.TWITCH_OAUTH_TOKEN
},
channels: [process.env.TWITCH_CHANNEL]
});
client.connect();
client.on('message', (channel, tags, message, self) => {
if (self) return;
if (message.toLowerCase() === '!hello') {
client.say(channel, `@${tags.username}, hello!`);
}
});
console.log('Twitch bot is running!');
Python Discord Bot Example
# main.py
import discord
import os
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def ping(ctx):
await ctx.send('Pong! 🏓')
@bot.command()
async def hello(ctx):
await ctx.send(f'Hello {ctx.author.mention}!')
# Use environment variable from dashboard
bot.run(os.getenv('DISCORD_TOKEN'))
Multi-language Support! You can use JavaScript, TypeScript, or Python for your bots. We automatically detect the language and install the right dependencies.
Frequently Asked Questions
Q: How many bots can I host?
A: Currently 10 bots per user. Need more? Contact us!
Q: Can I use private GitHub repositories?
A: Not yet, but we're working on GitHub authentication for private repos.
Q: My bot keeps crashing, what should I do?
A: Check the logs in your dashboard. Common issues: missing environment variables, invalid credentials, or unhandled errors in your code.
Q: How do I update my bot's code?
A: Currently, you need to delete the bot and redeploy. We're working on a "pull & restart" feature!
Q: Why was my bot rejected during deployment?
A: Check for security issues - file system access, shell commands, eval(), or unapproved packages. The error message will tell you what was detected.
Q: Can I connect to external databases?
A: Yes! Use the approved database packages (pg, mysql2, mongodb, redis) and store connection strings in environment variables.
Q: What's the difference between persistent and scheduled bots?
A: Persistent bots run 24/7 (great for Discord chat bots). Scheduled bots run at specific intervals like every hour or daily (great for automated posts or data collection).
Q: Can I run a scheduled bot every 5 minutes?
A: No, the minimum interval is 20 minutes to prevent server abuse. You can run bots every 20 min, 30 min, hourly, or longer.
Q: How do I change my bot from persistent to scheduled?
A: Click the "Edit Schedule" button on your bot card, select "Scheduled" mode, pick your schedule, and save!
Q: My scheduled bot shows "stopped" - is it broken?
A: No! Scheduled bots show "stopped" while waiting for the next run. Check the "Next run" time on your bot card to see when it will execute.
Q: Can I use both JavaScript and Python bots?
A: Yes! We support JavaScript, TypeScript, and Python. We automatically detect your language and install the right dependencies.
Q: Is this service free?
A: Currently yes! We may introduce premium tiers in the future with more resources and features.