How to use --setup to schedule tasks

app.py creates and reuses example files when users click “Download Example File,” while setup.py runs alongside it, clearing out cached files every 5 seconds to keep the directory clean.

app.py

# download button that writes a file to disk and serves it to the user using panel FileDownload callback

import random
import panel as pn
from pathlib import Path

pn.extension()

BASE_FILE_DIR = Path(__file__).parent / "examples"
BASE_FILE_DIR.mkdir(exist_ok=True)


def create_file():
    file_path = BASE_FILE_DIR / f"example_{random.randint(1, 3)}.txt"
    if file_path.exists():
        print("Reusing existing file:", file_path)
        return file_path

    with open(file_path, "w") as f:
        print("Creating new file:", file_path)
        f.write(
            "This is an example file. Random number: " + str(random.randint(1, 100))
        )
    return file_path


file_download = pn.widgets.FileDownload(
    filename="example.txt",
    button_type="primary",
    callback=create_file,
    label="Download Example File",
)
print("File download widget created:", file_download, flush=True)
pn.Column("# File Download Example", file_download).servable()

setup.py

# Every 5 seconds, clears out the examples directory
import panel as pn
from pathlib import Path

BASE_FILE_DIR = Path(__file__).parent / "examples"
BASE_FILE_DIR.mkdir(exist_ok=True)


def setup():
    print("Starting periodic cleanup of example files...")
    for file in BASE_FILE_DIR.iterdir():
        if file.is_file():
            print(file)
            file.unlink()

pn.state.schedule_task('task', setup, period='5s')

Run:
panel serve app.py --setup setup.py