We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
--autoreload does not work in Panel 1.2.2
Run this code with `panel serve --autoreload tmp.py` and change the end to 2 the 

``` python
# tmp.py
import panel as pn

pn.widgets.IntSlider(end=1).servable()
```

A git bisect indicates https://github.com/holoviz/panel/pull/5344 is the culprit. 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `panel/io/callbacks.py`
Content:
```
1 """
2 Defines callbacks to be executed on a thread or by scheduling it
3 on a running bokeh server.
4 """
5 import asyncio
6 import inspect
7 import logging
8 import time
9 
10 from functools import partial
11 
12 import param
13 
14 from ..util import edit_readonly, function_name
15 from .logging import LOG_PERIODIC_END, LOG_PERIODIC_START
16 from .state import curdoc_locked, state
17 
18 log = logging.getLogger('panel.callbacks')
19 _periodic_logger = logging.getLogger(f'{__name__}.PeriodicCallback')
20 
21 class PeriodicCallback(param.Parameterized):
22     """
23     Periodic encapsulates a periodic callback which will run both
24     in tornado based notebook environments and on bokeh server. By
25     default the callback will run until the stop method is called,
26     but count and timeout values can be set to limit the number of
27     executions or the maximum length of time for which the callback
28     will run. The callback may also be started and stopped by setting
29     the running parameter to True or False respectively.
30     """
31 
32     callback = param.Callable(doc="""
33         The callback to execute periodically.""")
34 
35     counter = param.Integer(default=0, doc="""
36         Counts the number of executions.""")
37 
38     count = param.Integer(default=None, doc="""
39         Number of times the callback will be executed, by default
40         this is unlimited.""")
41 
42     log = param.Boolean(default=True, doc="""
43         Whether the periodic callback should log its actions.""")
44 
45     period = param.Integer(default=500, doc="""
46         Period in milliseconds at which the callback is executed.""")
47 
48     timeout = param.Integer(default=None, doc="""
49         Timeout in milliseconds from the start time at which the callback
50         expires.""")
51 
52     running = param.Boolean(default=False, doc="""
53         Toggles whether the periodic callback is currently running.""")
54 
55     def __init__(self, **params):
56         self._background = params.pop('background', False)
57         super().__init__(**params)
58         self._start_time = None
59         self._cb = None
60         self._updating = False
61         self._doc = None
62 
63     @param.depends('running', watch=True)
64     def _start(self):
65         if not self.running or self._updating:
66             return
67         self.start()
68 
69     @param.depends('running', watch=True)
70     def _stop(self):
71         if self.running or self._updating:
72             return
73         self.stop()
74 
75     @param.depends('period', watch=True)
76     def _update_period(self):
77         if self._cb:
78             self.stop()
79             self.start()
80 
81     def _exec_callback(self, post=False):
82         from .state import set_curdoc
83         try:
84             with set_curdoc(self._doc):
85                 if self.running:
86                     self.counter += 1
87                     if self.counter > self.count:
88                         self.stop()
89                 cb = self.callback() if self.running else None
90         except Exception:
91             cb = None
92         if post:
93             self._post_callback()
94         return cb
95 
96     def _post_callback(self):
97         cbname = function_name(self.callback)
98         if self._doc and self.log:
99             _periodic_logger.info(
100                 LOG_PERIODIC_END, id(self._doc), cbname, self.counter
101             )
102         if not self._background:
103             with edit_readonly(state):
104                 state._busy_counter -= 1
105         if self.timeout is not None:
106             dt = (time.time() - self._start_time) * 1000
107             if dt > self.timeout:
108                 self.stop()
109         if self.counter == self.count:
110             self.stop()
111 
112     async def _periodic_callback(self):
113         if not self._background:
114             with edit_readonly(state):
115                 state._busy_counter += 1
116         cbname = function_name(self.callback)
117         if self._doc and self.log:
118             _periodic_logger.info(
119                 LOG_PERIODIC_START, id(self._doc), cbname, self.counter
120             )
121         is_async = (
122             inspect.isasyncgenfunction(self.callback) or
123             inspect.iscoroutinefunction(self.callback)
124         )
125         if state._thread_pool and not is_async:
126             future = state._thread_pool.submit(self._exec_callback, True)
127             future.add_done_callback(partial(state._handle_future_exception, doc=self._doc))
128             return
129         try:
130             cb = self._exec_callback()
131             if inspect.isawaitable(cb):
132                 await cb
133         except Exception:
134             log.exception('Periodic callback failed.')
135             raise
136         finally:
137             self._post_callback()
138 
139     async def _async_repeat(self, func):
140         """
141         Run func every interval seconds.
142 
143         If func has not finished before *interval*, will run again
144         immediately when the previous iteration finished.
145         """
146         while True:
147             start = time.monotonic()
148             await func()
149             timeout = (self.period/1000.) - (time.monotonic()-start)
150             if timeout > 0:
151                 await asyncio.sleep(timeout)
152 
153     def _cleanup(self, session_context):
154         self.stop()
155 
156     def start(self):
157         """
158         Starts running the periodic callback.
159         """
160         if self._cb is not None:
161             raise RuntimeError('Periodic callback has already started.')
162         if not self.running:
163             try:
164                 self._updating = True
165                 self.running = True
166             finally:
167                 self._updating = False
168         self._start_time = time.time()
169         if state._is_pyodide:
170             self._cb = asyncio.create_task(
171                 self._async_repeat(self._periodic_callback)
172             )
173         elif state.curdoc and state.curdoc.session_context:
174             self._doc = state.curdoc
175             if state._unblocked(state.curdoc):
176                 self._cb = self._doc.add_periodic_callback(self._periodic_callback, self.period)
177             else:
178                 self._doc.add_next_tick_callback(self.start)
179         else:
180             from tornado.ioloop import PeriodicCallback
181             self._cb = PeriodicCallback(lambda: asyncio.create_task(self._periodic_callback()), self.period)
182             self._cb.start()
183 
184     def stop(self):
185         """
186         Stops running the periodic callback.
187         """
188         if self.running:
189             try:
190                 self._updating = True
191                 self.running = False
192             finally:
193                 self._updating = False
194         with param.discard_events(self):
195             self.counter = 0
196         self._timeout = None
197         if state._is_pyodide:
198             self._cb.cancel()
199         elif self._doc:
200             if self._doc._session_context:
201                 self._doc.callbacks.remove_session_callback(self._cb)
202             else:
203                 self._doc.callbacks._session_callbacks.remove(self._cb)
204         elif self._cb:
205             self._cb.stop()
206         self._cb = None
207         doc = self._doc or curdoc_locked()
208         if doc:
209             doc.callbacks.session_destroyed_callbacks = {
210                 cb for cb in doc.callbacks.session_destroyed_callbacks
211                 if cb is not self._cleanup
212             }
213             self._doc = None
214
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/panel/io/callbacks.py b/panel/io/callbacks.py
--- a/panel/io/callbacks.py
+++ b/panel/io/callbacks.py
@@ -84,7 +84,7 @@
             with set_curdoc(self._doc):
                 if self.running:
                     self.counter += 1
-                    if self.counter > self.count:
+                    if self.count is not None and self.counter > self.count:
                         self.stop()
                 cb = self.callback() if self.running else None
         except Exception:

{"golden_diff": "diff --git a/panel/io/callbacks.py b/panel/io/callbacks.py\n--- a/panel/io/callbacks.py\n+++ b/panel/io/callbacks.py\n@@ -84,7 +84,7 @@\n             with set_curdoc(self._doc):\n                 if self.running:\n                     self.counter += 1\n-                    if self.counter > self.count:\n+                    if self.count is not None and self.counter > self.count:\n                         self.stop()\n                 cb = self.callback() if self.running else None\n         except Exception:\n", "issue": "--autoreload does not work in Panel 1.2.2\nRun this code with `panel serve --autoreload tmp.py` and change the end to 2 the \r\n\r\n``` python\r\n# tmp.py\r\nimport panel as pn\r\n\r\npn.widgets.IntSlider(end=1).servable()\r\n```\r\n\r\nA git bisect indicates https://github.com/holoviz/panel/pull/5344 is the culprit. \n", "before_files": [{"content": "\"\"\"\nDefines callbacks to be executed on a thread or by scheduling it\non a running bokeh server.\n\"\"\"\nimport asyncio\nimport inspect\nimport logging\nimport time\n\nfrom functools import partial\n\nimport param\n\nfrom ..util import edit_readonly, function_name\nfrom .logging import LOG_PERIODIC_END, LOG_PERIODIC_START\nfrom .state import curdoc_locked, state\n\nlog = logging.getLogger('panel.callbacks')\n_periodic_logger = logging.getLogger(f'{__name__}.PeriodicCallback')\n\nclass PeriodicCallback(param.Parameterized):\n    \"\"\"\n    Periodic encapsulates a periodic callback which will run both\n    in tornado based notebook environments and on bokeh server. By\n    default the callback will run until the stop method is called,\n    but count and timeout values can be set to limit the number of\n    executions or the maximum length of time for which the callback\n    will run. The callback may also be started and stopped by setting\n    the running parameter to True or False respectively.\n    \"\"\"\n\n    callback = param.Callable(doc=\"\"\"\n        The callback to execute periodically.\"\"\")\n\n    counter = param.Integer(default=0, doc=\"\"\"\n        Counts the number of executions.\"\"\")\n\n    count = param.Integer(default=None, doc=\"\"\"\n        Number of times the callback will be executed, by default\n        this is unlimited.\"\"\")\n\n    log = param.Boolean(default=True, doc=\"\"\"\n        Whether the periodic callback should log its actions.\"\"\")\n\n    period = param.Integer(default=500, doc=\"\"\"\n        Period in milliseconds at which the callback is executed.\"\"\")\n\n    timeout = param.Integer(default=None, doc=\"\"\"\n        Timeout in milliseconds from the start time at which the callback\n        expires.\"\"\")\n\n    running = param.Boolean(default=False, doc=\"\"\"\n        Toggles whether the periodic callback is currently running.\"\"\")\n\n    def __init__(self, **params):\n        self._background = params.pop('background', False)\n        super().__init__(**params)\n        self._start_time = None\n        self._cb = None\n        self._updating = False\n        self._doc = None\n\n    @param.depends('running', watch=True)\n    def _start(self):\n        if not self.running or self._updating:\n            return\n        self.start()\n\n    @param.depends('running', watch=True)\n    def _stop(self):\n        if self.running or self._updating:\n            return\n        self.stop()\n\n    @param.depends('period', watch=True)\n    def _update_period(self):\n        if self._cb:\n            self.stop()\n            self.start()\n\n    def _exec_callback(self, post=False):\n        from .state import set_curdoc\n        try:\n            with set_curdoc(self._doc):\n                if self.running:\n                    self.counter += 1\n                    if self.counter > self.count:\n                        self.stop()\n                cb = self.callback() if self.running else None\n        except Exception:\n            cb = None\n        if post:\n            self._post_callback()\n        return cb\n\n    def _post_callback(self):\n        cbname = function_name(self.callback)\n        if self._doc and self.log:\n            _periodic_logger.info(\n                LOG_PERIODIC_END, id(self._doc), cbname, self.counter\n            )\n        if not self._background:\n            with edit_readonly(state):\n                state._busy_counter -= 1\n        if self.timeout is not None:\n            dt = (time.time() - self._start_time) * 1000\n            if dt > self.timeout:\n                self.stop()\n        if self.counter == self.count:\n            self.stop()\n\n    async def _periodic_callback(self):\n        if not self._background:\n            with edit_readonly(state):\n                state._busy_counter += 1\n        cbname = function_name(self.callback)\n        if self._doc and self.log:\n            _periodic_logger.info(\n                LOG_PERIODIC_START, id(self._doc), cbname, self.counter\n            )\n        is_async = (\n            inspect.isasyncgenfunction(self.callback) or\n            inspect.iscoroutinefunction(self.callback)\n        )\n        if state._thread_pool and not is_async:\n            future = state._thread_pool.submit(self._exec_callback, True)\n            future.add_done_callback(partial(state._handle_future_exception, doc=self._doc))\n            return\n        try:\n            cb = self._exec_callback()\n            if inspect.isawaitable(cb):\n                await cb\n        except Exception:\n            log.exception('Periodic callback failed.')\n            raise\n        finally:\n            self._post_callback()\n\n    async def _async_repeat(self, func):\n        \"\"\"\n        Run func every interval seconds.\n\n        If func has not finished before *interval*, will run again\n        immediately when the previous iteration finished.\n        \"\"\"\n        while True:\n            start = time.monotonic()\n            await func()\n            timeout = (self.period/1000.) - (time.monotonic()-start)\n            if timeout > 0:\n                await asyncio.sleep(timeout)\n\n    def _cleanup(self, session_context):\n        self.stop()\n\n    def start(self):\n        \"\"\"\n        Starts running the periodic callback.\n        \"\"\"\n        if self._cb is not None:\n            raise RuntimeError('Periodic callback has already started.')\n        if not self.running:\n            try:\n                self._updating = True\n                self.running = True\n            finally:\n                self._updating = False\n        self._start_time = time.time()\n        if state._is_pyodide:\n            self._cb = asyncio.create_task(\n                self._async_repeat(self._periodic_callback)\n            )\n        elif state.curdoc and state.curdoc.session_context:\n            self._doc = state.curdoc\n            if state._unblocked(state.curdoc):\n                self._cb = self._doc.add_periodic_callback(self._periodic_callback, self.period)\n            else:\n                self._doc.add_next_tick_callback(self.start)\n        else:\n            from tornado.ioloop import PeriodicCallback\n            self._cb = PeriodicCallback(lambda: asyncio.create_task(self._periodic_callback()), self.period)\n            self._cb.start()\n\n    def stop(self):\n        \"\"\"\n        Stops running the periodic callback.\n        \"\"\"\n        if self.running:\n            try:\n                self._updating = True\n                self.running = False\n            finally:\n                self._updating = False\n        with param.discard_events(self):\n            self.counter = 0\n        self._timeout = None\n        if state._is_pyodide:\n            self._cb.cancel()\n        elif self._doc:\n            if self._doc._session_context:\n                self._doc.callbacks.remove_session_callback(self._cb)\n            else:\n                self._doc.callbacks._session_callbacks.remove(self._cb)\n        elif self._cb:\n            self._cb.stop()\n        self._cb = None\n        doc = self._doc or curdoc_locked()\n        if doc:\n            doc.callbacks.session_destroyed_callbacks = {\n                cb for cb in doc.callbacks.session_destroyed_callbacks\n                if cb is not self._cleanup\n            }\n            self._doc = None\n", "path": "panel/io/callbacks.py"}], "after_files": [{"content": "\"\"\"\nDefines callbacks to be executed on a thread or by scheduling it\non a running bokeh server.\n\"\"\"\nimport asyncio\nimport inspect\nimport logging\nimport time\n\nfrom functools import partial\n\nimport param\n\nfrom ..util import edit_readonly, function_name\nfrom .logging import LOG_PERIODIC_END, LOG_PERIODIC_START\nfrom .state import curdoc_locked, state\n\nlog = logging.getLogger('panel.callbacks')\n_periodic_logger = logging.getLogger(f'{__name__}.PeriodicCallback')\n\nclass PeriodicCallback(param.Parameterized):\n    \"\"\"\n    Periodic encapsulates a periodic callback which will run both\n    in tornado based notebook environments and on bokeh server. By\n    default the callback will run until the stop method is called,\n    but count and timeout values can be set to limit the number of\n    executions or the maximum length of time for which the callback\n    will run. The callback may also be started and stopped by setting\n    the running parameter to True or False respectively.\n    \"\"\"\n\n    callback = param.Callable(doc=\"\"\"\n        The callback to execute periodically.\"\"\")\n\n    counter = param.Integer(default=0, doc=\"\"\"\n        Counts the number of executions.\"\"\")\n\n    count = param.Integer(default=None, doc=\"\"\"\n        Number of times the callback will be executed, by default\n        this is unlimited.\"\"\")\n\n    log = param.Boolean(default=True, doc=\"\"\"\n        Whether the periodic callback should log its actions.\"\"\")\n\n    period = param.Integer(default=500, doc=\"\"\"\n        Period in milliseconds at which the callback is executed.\"\"\")\n\n    timeout = param.Integer(default=None, doc=\"\"\"\n        Timeout in milliseconds from the start time at which the callback\n        expires.\"\"\")\n\n    running = param.Boolean(default=False, doc=\"\"\"\n        Toggles whether the periodic callback is currently running.\"\"\")\n\n    def __init__(self, **params):\n        self._background = params.pop('background', False)\n        super().__init__(**params)\n        self._start_time = None\n        self._cb = None\n        self._updating = False\n        self._doc = None\n\n    @param.depends('running', watch=True)\n    def _start(self):\n        if not self.running or self._updating:\n            return\n        self.start()\n\n    @param.depends('running', watch=True)\n    def _stop(self):\n        if self.running or self._updating:\n            return\n        self.stop()\n\n    @param.depends('period', watch=True)\n    def _update_period(self):\n        if self._cb:\n            self.stop()\n            self.start()\n\n    def _exec_callback(self, post=False):\n        from .state import set_curdoc\n        try:\n            with set_curdoc(self._doc):\n                if self.running:\n                    self.counter += 1\n                    if self.count is not None and self.counter > self.count:\n                        self.stop()\n                cb = self.callback() if self.running else None\n        except Exception:\n            cb = None\n        if post:\n            self._post_callback()\n        return cb\n\n    def _post_callback(self):\n        cbname = function_name(self.callback)\n        if self._doc and self.log:\n            _periodic_logger.info(\n                LOG_PERIODIC_END, id(self._doc), cbname, self.counter\n            )\n        if not self._background:\n            with edit_readonly(state):\n                state._busy_counter -= 1\n        if self.timeout is not None:\n            dt = (time.time() - self._start_time) * 1000\n            if dt > self.timeout:\n                self.stop()\n        if self.counter == self.count:\n            self.stop()\n\n    async def _periodic_callback(self):\n        if not self._background:\n            with edit_readonly(state):\n                state._busy_counter += 1\n        cbname = function_name(self.callback)\n        if self._doc and self.log:\n            _periodic_logger.info(\n                LOG_PERIODIC_START, id(self._doc), cbname, self.counter\n            )\n        is_async = (\n            inspect.isasyncgenfunction(self.callback) or\n            inspect.iscoroutinefunction(self.callback)\n        )\n        if state._thread_pool and not is_async:\n            future = state._thread_pool.submit(self._exec_callback, True)\n            future.add_done_callback(partial(state._handle_future_exception, doc=self._doc))\n            return\n        try:\n            cb = self._exec_callback()\n            if inspect.isawaitable(cb):\n                await cb\n        except Exception:\n            log.exception('Periodic callback failed.')\n            raise\n        finally:\n            self._post_callback()\n\n    async def _async_repeat(self, func):\n        \"\"\"\n        Run func every interval seconds.\n\n        If func has not finished before *interval*, will run again\n        immediately when the previous iteration finished.\n        \"\"\"\n        while True:\n            start = time.monotonic()\n            await func()\n            timeout = (self.period/1000.) - (time.monotonic()-start)\n            if timeout > 0:\n                await asyncio.sleep(timeout)\n\n    def _cleanup(self, session_context):\n        self.stop()\n\n    def start(self):\n        \"\"\"\n        Starts running the periodic callback.\n        \"\"\"\n        if self._cb is not None:\n            raise RuntimeError('Periodic callback has already started.')\n        if not self.running:\n            try:\n                self._updating = True\n                self.running = True\n            finally:\n                self._updating = False\n        self._start_time = time.time()\n        if state._is_pyodide:\n            self._cb = asyncio.create_task(\n                self._async_repeat(self._periodic_callback)\n            )\n        elif state.curdoc and state.curdoc.session_context:\n            self._doc = state.curdoc\n            if state._unblocked(state.curdoc):\n                self._cb = self._doc.add_periodic_callback(self._periodic_callback, self.period)\n            else:\n                self._doc.add_next_tick_callback(self.start)\n        else:\n            from tornado.ioloop import PeriodicCallback\n            self._cb = PeriodicCallback(lambda: asyncio.create_task(self._periodic_callback()), self.period)\n            self._cb.start()\n\n    def stop(self):\n        \"\"\"\n        Stops running the periodic callback.\n        \"\"\"\n        if self.running:\n            try:\n                self._updating = True\n                self.running = False\n            finally:\n                self._updating = False\n        with param.discard_events(self):\n            self.counter = 0\n        self._timeout = None\n        if state._is_pyodide:\n            self._cb.cancel()\n        elif self._doc:\n            if self._doc._session_context:\n                self._doc.callbacks.remove_session_callback(self._cb)\n            else:\n                self._doc.callbacks._session_callbacks.remove(self._cb)\n        elif self._cb:\n            self._cb.stop()\n        self._cb = None\n        doc = self._doc or curdoc_locked()\n        if doc:\n            doc.callbacks.session_destroyed_callbacks = {\n                cb for cb in doc.callbacks.session_destroyed_callbacks\n                if cb is not self._cleanup\n            }\n            self._doc = None\n", "path": "panel/io/callbacks.py"}]}